推理其实很简单,因为$in和$all有两个完全不同的功能。该文件的链接存在,但解释:
考虑这些文件:
{
_id: 1,
items: [ "a", "b" ]
},
{
_id: 2,
items: [ "a", "b", "c" ]
}
$在 - 提供了可能匹配在现场被测试的值参数的列表。这将匹配如下:
db.collection.find({ items: {$in: [ "a", "b", "c" ] }})
{
_id: 1,
items: [ "a", "b" ]
},
{
_id: 2,
items: [ "a", "b", "c" ]
}
$所有 - 提供其中被匹配字段被预期是一个数组和所列出的元件的所有存在该数组中的列表。 E.g
db.collection.find({ items: {$all: [ "a", "b", "c" ] }})
{
_id: 2,
items: [ "a", "b", "c" ]
}
因此,为什么您的查询不返回结果,本场是不是数组,不包含都元素。
MongoDB operator reference是你应该真正通读。
正如你对你的说法,[“我需要找到所有文档与_id 1和2,如果从他们那里有人不存在,那么失败。”],匹配不同的标准是容易为你的使用看$ in。你的问题是你想要一个整套匹配或以其他方式返回(“失败”)。这我已经在previous question给你解释的一些长度,但再次重申:
db.collection.aggregate([
// Match on what you want to find
{$match: { list: {$in: [1,2]} }},
// Add the found results to a distinct *set*
{$group: { _id: null, list: {$addToSet: "$_id"} }},
// Only return when *all* the expected items are in the *set*
{$match: { list: {$all: [1,2]} }}
])
这样操作之后,这样只会返回一个结果的项目,如果所有地方发现的。这就是我们如何使用$全部以这种方式匹配。
感谢您的回应,但我怎么能得到所有文件与_id 1和2或失败,如果其中一个不存在? – Erik
@Erik我扩大了用法。这应该更好地解释。我也在你之前的问题中解释了你的评论(不是你的问题)http://stackoverflow.com/a/21881817/2313887 –
@Erik最终编辑来清除这个问题。 –