简体   繁体   English

在MongoDB / mongoose中查询字符串时$ or和$ in之间的区别

[英]Differences between $or and $in when querying Strings in MongoDB / mongoose

While building an API, I need to match documents that contain pending or active values for the key status . 在构建一个API,我需要匹配包含文件pendingactive的键值status

When trying 尝试时

args.status = {
  $or: [
    'active',
    'pending'
  ]
}

I get an error: cannot use $or with string 我收到一个错误: cannot use $or with string

However, 然而,

args.status = {
  $in: [
    'active',
    'pending'
  ]
}

works just fine. 效果很好。

I would expect $or to work here. 我希望$or在这里工作。 Can someone provide context on the differences between the two and why Strings require $in ? 有人可以提供关于两者之间差异的上下文,以及为什么字符串需要$in吗?

Thats because $or expects array of objects. 那是因为$ or需要对象数组。 Objects that defines some filters out of which at least one needs to be match to return the result. 定义一些过滤器的对象,至少要匹配其中的一个过滤器才能返回结果。 For your particular scenario $in is the best option. 对于您的特定情况, $ in是最佳选择。 Still if you wanna go with $or , the query will be like: 仍然,如果您想使用$ or ,查询将类似于:

{
  $or: [
    {'args.status' : {$eq: 'active'}},
    {'args.status' : {$eq: 'pending'}}
  ]
}

I'd suggest you stick with $in as it is the best fit for your requirement. 我建议您坚持使用$ in,因为它最适合您的要求。

You can check the official docs for more details on $or 您可以查看官方文档以获取有关$ or的更多详细信息

Hope this helps :) 希望这可以帮助 :)

$or performs the logical OR operation on an ARRAY with more than two expressions eg {$or:[{name:"a"},{name:"b"}]} This query will return the record which are having either name 'a' or 'b'. $ or在具有两个以上表达式的ARRAY上执行逻辑OR操作,例如{$or:[{name:"a"},{name:"b"}]}该查询将返回名称为' a”或“ b”。

$in works on the array and return the documents which are which contains any of the field from your specified array eg {name:{$in:['a','b']}} This query will return the documents where name is either 'a' or 'b'. $ in在数组上工作并返回包含指定数组中任何字段的文档,例如{name:{$in:['a','b']}}此查询将返回name为A或B'。

Ideally both are doing same but just having the syntax difference. 理想情况下,两者都是一样的,只是语法有所不同。

In your case you have to modify your OR query syntax and add the condition expessions in an ARRAY. 在您的情况下,您必须修改OR查询语法,并在阵列中添加条件expessions。

{ $or: [
    {
      "args.status": "active"
    },
    {
      "args.status": "pending"
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM