简体   繁体   English

流星/ MongoDB:按相同属性的多个值查找文档

[英]Meteor/MongoDB: find documents by multiple values of same property

I need to find a couple of documents which have specific colors. 我需要找到一些具有特定颜色的文档。 I've search this place and was able to construct the following query: 我已经搜索了这个地方,并能够构建以下查询:

db.tasks.find({$or: { color:  {$all: ['e4oqPeoBTJtCpG53K', 'cvmQv7vQHunPnmqPz'] }}});

What I'm trying here is to find all documents which have a color of e4o... and cvmQ.. But this doesn't work at all. 我在这里尝试的是查找所有颜色为e4o...cvmQ..但这根本不起作用。 Any suggestions what I do wrong ? 有什么建议我做错了吗?

If you just want to find the the documents that only contain the specified color values you can use this form with the $and operator and the use of $size : 如果您只想查找包含指定颜色值的文档,则可以将此表单与$and运算符以及$size使用:

db.tasks.find({ "$and": [
    { "color": "e4oqPeoBTJtCpG53K" },
    { "color": "cvmQv7vQHunPnmqP"' },
    { "color": { "$size": 2 } }

]} ]}

And this simplifies a little with the MongoDB 2.6 and upwards releases by actually fixing the proper use of $all as an operator so that it behaves much like logical $and but with better syntax: 通过实际修复$all作为运算符的正确用法,这在MongoDB 2.6和更高版本中进行了一些简化,使其行为与逻辑$and相似$and但语法更好:

db.tasks.find({ "$and": [
   {"color": {
       "$all": [ "e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz" ]
   },
   { "color": { "$size": 2 } }

]} ]}

Or even another way of writing the same thing is like this using logical $or : 甚至是写同一件事的另一种方式是使用逻辑$or

db.tasks.find({ "$and": [
   "$or": [
       {"color": [ "e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz" ]  },
       {"color": [ "cvmQv7vQHunPnmqPz", "e4oqPeoBTJtCpG53K" ]  }
   ],
   { "color": { "$size": 2 } }
]}

If the array must contain both of those elements and possibly more then the simple form is with the $and constraint alone: 如果数组必须同时包含这两个元素,并且可能包含更多元素,则简单形式是仅使用$and约束:

db.tasks.find({ "$and": [
    { "color": "e4oqPeoBTJtCpG53K" },
    { "color": "cvmQv7vQHunPnmqP"' }
]}

And if "any" element in any document this is a logical $or best specified with the $in operator 而且,如果任何文档中的“任何”元素都是逻辑$or最好用$in运算符指定

db.tasks.find({
    "color":  {
        "$in": ["e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz"] 
    }
})

Whatever you actually want to do, there should be enough options there. 无论您实际上想做什么,都应该有足够的选择。

Please also note that these will work with the "server side" implementation, but mileage on the "client" side using "minimongo" may differ due to the support in that client side code. 另请注意,这些方法可与“服务器端”实现一起使用,但是由于该客户端代码的支持,使用“ minimongo”的“客户端”端的里程可能会有所不同。

尝试不使用$or ,并使用$in (如果要查找具有列出颜色的文档),(如果需要具有所有列出颜色的文档,则使用$ all)。

db.tasks.find({ color:  {$in: ['e4oqPeoBTJtCpG53K', 'cvmQv7vQHunPnmqPz'] }});

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

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