我有以下文件:
{
_id: 1
title: "oneItem"
},
{
_id: 2,
title: "twoItem"
}
当我尝试使用以下命令查找这些文档时:
db.collection.documents.find({_id: {$in: [1, 2]}});
我得到了这两个文档,但是当我尝试使用以下查询查找这些文档时:
db.collection.documents.find({_id: {$all: [1, 2]}});
我什么也没得到。你能解释一下有什么问题吗?基本上我需要找到所有 _id 1 和 2 的文档,如果不存在则失败。
最佳答案
推理实际上很简单 $in和 $all具有两种完全不同的功能。文档链接在那里,但要解释一下:
考虑这些文档:
{
_id: 1,
items: [ "a", "b" ]
},
{
_id: 2,
items: [ "a", "b", "c" ]
}
$in - 提供可能与正在测试的字段中的值匹配的参数列表。这将匹配如下:
db.collection.find({ items: {$in: [ "a", "b", "c" ] }})
{
_id: 1,
items: [ "a", "b" ]
},
{
_id: 2,
items: [ "a", "b", "c" ]
}
$all - 提供一个列表,其中匹配的字段预计是一个数组,并且所有列出的元素都存在于该数组中。例如
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]} }}
])
因此,在该操作之后,仅当找到所有项目时才会返回结果。这就是我们使用$all这样的方式进行匹配。
关于javascript - 为什么找不到带有 '$all' 修饰符的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897819/