【问题标题】:Can $in and $or replace each other in MongoDB?$in 和 $or 在 MongoDB 中可以互相替换吗?
【发布时间】:2020-05-22 18:44:25
【问题描述】:

$in 和 $or 在 MongoDB 中可以互相替换吗?

db.restaurants.find(
{
  "borough" :{$in :["Staten Island","Queens","Bronx","Brooklyn"]}},
  {
    "restaurant_id" : 1,
    "name":1,"borough":1,
    "cuisine" :1
  }
);


db.restaurants.find(
{ 
"borough": "Bronx" , 
  $or : [
          { "cuisine" : "American " },
          { "cuisine" : "Chinese" }
        ] 
} 
);

我观察到这两个查询都需要我们从一些选项中进行选择:

将第一个查询中的 $in 替换为 $or 是否有意义,如下所示:

db.restaurants.find(
{ $or: [{ borough: 'Staten Island',
          borough: 'Queens',
          borough: 'Bronx',
          borough: 'Brooklyn' }],

  { _id : 1,
    name: 1,
    borough : 1,
    cuisine : 1
  }
 })

$in 和 $or 可以替换吗?

更新:
我尝试使用两个查询,希望得到相同的结果:

为什么第二个查询只选择了两行状态“D”?

> db.inventory.find( {status : { $in: [ 'A', 'D'] }}, {item:1, status: 1})
{ "_id" : ObjectId("5eb67598bee5213484d45087"), "item" : "journal", "status" : "A" }
{ "_id" : ObjectId("5eb67598bee5213484d45088"), "item" : "notebook", "status" : "A" }
{ "_id" : ObjectId("5eb67598bee5213484d45089"), "item" : "paper", "status" : "D" }
{ "_id" : ObjectId("5eb67598bee5213484d4508a"), "item" : "planner", "status" : "D" }
{ "_id" : ObjectId("5eb67598bee5213484d4508b"), "item" : "postcard", "status" : "A" }
>
>
> db.inventory.find( {$or: [ {status: 'A', status: 'D'} ] }, {item:1, status: 1})
{ "_id" : ObjectId("5eb67598bee5213484d45089"), "item" : "paper", "status" : "D" }
{ "_id" : ObjectId("5eb67598bee5213484d4508a"), "item" : "planner", "status" : "D" }
> 

【问题讨论】:

    标签: database mongodb nosql


    【解决方案1】:

    来自他们的官方文档本身or-versus-in

    当使用 $or 时,会检查 相同字段的值,使用 $in 运算符而不是 $or 运算符。

    如果您有以下文档:

    [
      {
        "price": 100
      },
      {
        "price": 200
      },
      {
        "price": 300
      },
      {
        "price": 400
      },
      {
        "price": 500
      }
    ]
    

    如果您想获得price 等于100500 的文档,请查询如下:

    db.collection.find({ price: { $in: [ 100, 500 ] } })
    

    通过上述操作,查询变得简单明了。您也可以使用$or 而不是$in,但是为什么要松散速记符号并尝试通过一次又一次地添加更多相同字段的对象来使查询看起来很庞大?

    默认情况下,如果您想对两个不同的运算符执行逻辑OR,您将使用$or,但何时在同一字段上使用$or

    db.collection.find({ $or: [ { price: { $lt: 200 } }, { price: { $gt: 400 } } ] })
    

    如上所述,当您在同一个字段上匹配多个不同的条件时,您将使用它。

    这两个查询在执行时产生相同的结果,但是当您使用 $in 时 - 如果输入值是直数或者可以是字符串或其他类型,其中输入值将与文档中的 price 字段的值完全匹配,但是当你使用$or 你正在检查同一字段的不同条件。

    测试: mongoplayground

    【讨论】:

    • 你的回答比较详细。让我的答案有利于你的。 +1
    • 我已经更新了这个问题。请添加更新后的答案。
    • The $or operator performs a logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions>. 这是否意味着 $or 必然会呈现只满足一个条件的结果?这就是为什么它只在我更新的问题中显示状态为“D”的结果?
    • 我明白了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-12-29
    • 2017-12-08
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多