MongoDB 一起使用 NOT 和 AND [英] MongoDB using NOT and AND together

查看:60
本文介绍了MongoDB 一起使用 NOT 和 AND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 MongoDB 否定 $and 子句,但我收到了 MongoError: invalid operator: $and 消息.基本上我想要实现的是以下内容:

I'm trying to negate an $and clause with MongoDB and I'm getting a MongoError: invalid operator: $and message back. Basically what I want to achieve is the following:

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

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

Is this possible to express in a mongo query?

这是一个示例集合:

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

我想找回的是以下内容:

What I want to get back is the following:

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

推荐答案

您正在寻找 NOT (A AND C),相当于 NOT A OR NOT C代码>:

You're looking for NOT (A AND C), which is equivalent to NOT A OR NOT C:

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

MongoDB 还有一个 $nor 逻辑运算符,它执行对一个或多个查询表达式的数组进行逻辑 NOR 操作,并选择使数组中所有查询表达式失败的文档",因此等效查询将是:

MongoDB also has a $nor logical operator that "performs a logical NOR operation on an array of one or more query expression and selects the documents that fail all the query expressions in the array", so an equivalent query would be:

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

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

The accepted answer recommends using a $where operator, but that is unnecessary here and taxes performance.

这篇关于MongoDB 一起使用 NOT 和 AND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆