gpt4 book ai didi

MongoDB 一起使用 NOT 和 AND

转载 作者:IT老高 更新时间:2023-10-28 13:08:32 25 4
gpt4 key购买 nike

我正在尝试用 MongoDB 否定 $and 子句,我收到了 MongoError: invalid operator: $and 消息。基本上我想要达到的目标如下:

query = { $not: { $and: [{institution_type:'A'}, {type:'C'}] } }

这可以在 mongo 查询中表达吗?

这是一个示例集合:

{ "institution_type" : "A", "type" : "C" }
{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }

我想要返回的是以下内容:

{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }

最佳答案

你正在寻找NOT (A AND C),它相当于NOT A OR NOT C:

db.collection.find({
"$or": [
{"institution_type": {"$ne": "A"}},
{"type": {"$ne": "C"}}
]
})

MongoDB 还有一个 $nor逻辑运算符“对一个或多个查询表达式的数组执行逻辑 NOR 运算,并选择数组中所有查询表达式失败的文档”,因此等效查询为:

db.collection.find({
"$nor": [
{"institution_type": "A"},
{"type": "C"}
]
})

接受的答案建议使用 $where 运算符,但这在此处是不必要的,并且会影响性​​能。

关于MongoDB 一起使用 NOT 和 AND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24092984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com