使用MongoDB排除符合条件的项

使用MongoDB排除符合条件的项,mongodb,mongodb-query,Mongodb,Mongodb Query,我有一个类似的项目列表: { user: "ObjectId(...)" type: "foo", subType: "foo_bar", state: "active", accounts: [ObjectId(...)] } 我需要创建一个MongoDB查询(我不太熟悉),如果状态为:“active”,则该查询将排除所有子类型:“foo\u bar” 查看我试图使用的文档时,$not,但我确实收到错误:未知顶级操作员:$not 正在尝试许多不需要在此报告的不同查询,因为

我有一个类似的项目列表:

{
  user: "ObjectId(...)"
  type: "foo",
  subType: "foo_bar",
  state: "active",
  accounts: [ObjectId(...)]
}
我需要创建一个MongoDB查询(我不太熟悉),如果
状态为:“active”
,则该查询将排除所有
子类型:“foo\u bar”

查看我试图使用的文档时,
$not
,但我确实收到错误:
未知顶级操作员:$not

正在尝试许多不需要在此报告的不同查询,因为它们都包含错误

这是工作正常的基本查询,我需要附加新条件:

db.items.find({ $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } })

有人能帮我做到这一点吗?谢谢

您可以恢复您的标准并将
$或
$ne
一起使用:

db.collection.find({ $or: [ { state: { $ne: "active" } }, { subType: { $ne: "foo_bar" } } ] })

只需使用
$和
运算符将其添加到现有查询中即可

db.collection.find({ $and: [ 
    { $or: [ { state: { $ne: "active" } }, { subType: { $ne: "foo_bar" } } ] },
    { $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } }
    ] })

您可以尝试类似于
db.items.find({“$or”:[{state:“active”,subType:{“$ne:“foo_bar”}},{state:{“$ne:“active”}]})

这将返回所有处于活动状态(但不是foo_bar)或未处于活动状态(任何子类型)的项

编辑:

将其添加到基本查询中应该类似于

db.items.find(
    {   "$and": [
            { $or: [{ user: myUser._id }, { accounts: { $in: myAccountsVariable } }], state: { $ne: "closed" } },
            {"$or": [{state: "active", subType: {"$ne": "foo_bar"}}, {state: {"$ne": "active"}}]}
        ]
    }
)