查询mongodb中的条件过滤器

3duebb1j  于 2023-01-01  发布在  Go
关注(0)|答案(1)|浏览(239)

我有3个用户角色存储在我的用户集合中[主管、市场、客户]。
市场想要执行搜索查询以找到用户,
我希望market能够列出除markets之外的所有用户,
我希望他能够只看到自己,而排除其他市场。
在现实生活中
数据如下所示:

[
  {
    "role": "supervisor",
    "name": "S1",
    "branch": "School #A",
    "id": 1
  },
  {
    "role": "market",
    "name": "M1",
    "branch": "School #A",
    "id": 2
  },
  {
    "role": "market",
    "name": "M2",
    "branch": "School #A",
    "id": 3
  },
  {
    "role": "client",
    "name": "C1",
    "branch": "School #A",
    "id": 4
  },
  {
    "role": "client",
    "name": "C2",
    "branch": "School #A",
    "id": 5
  }
]

我想执行一个查询,该查询应返回以下输出:

[
  {
    "role": "supervisor",
    "name": "S1",
    "branch": "School #A",
    "id": 1
  },
  {
    "role": "market",
    "name": "M1",
    "branch": "School #A",
    "id": 2
  },
  {
    "role": "client",
    "name": "C1",
    "branch": "School #A",
    "id": 4
  },
  {
    "role": "client",
    "name": "C2",
    "branch": "School #A",
    "id": 5
  }
]

查询应排除此文档:

{
    "role": "market",
    "name": "M2",
    "branch": "School #A",
    "id": 3
  }

如何执行此查询。
我用的是mongosh

# this is how the command looks like at the moment:
$ db.users.find({  })

请注意:
我不能这样做:

# this is how the command looks like at the moment:
$ db.users.find({ id: { $ne: 3 } })

因为每天都会有更多的用户(市场)注册。

ruarlubt

ruarlubt1#

您可以使用$or来执行以下操作:

db.collection.find({
  $or: [
    {role: {$ne: "market"}},
    {id: 2}
  ]
})

了解它在playground example上的工作原理

相关问题