我有如下所示的文件:
{
name: "testing",
place:"London",
documents: [
{
x:1,
y:2,
},
{
x:1,
y:3,
},
{
x:4,
y:3,
}
]
}
我想检索所有匹配的文档,即我想要以下格式的 o/p:
{
name: "testing",
place:"London",
documents: [
{
x:1,
y:2,
},
{
x:1,
y:3,
}
]
}
我尝试过的是:
db.test.find({"documents.x": 1},{_id: 0, documents: {$elemMatch: {x: 1}}});
但是,它只提供第一个条目。
最佳答案
正如JohnnyHK所说,答案在MongoDB: select matched elements of subcollection很好地解释了它。
在您的情况下,聚合如下所示:
(注意:第一次匹配不是绝对必要的,但它在性能(可以使用索引)和内存使用(有限集上的 $unwind )方面有所帮助
> db.xx.aggregate([
... // find the relevant documents in the collection
... // uses index, if defined on documents.x
... { $match: { documents: { $elemMatch: { "x": 1 } } } },
... // flatten array documennts
... { $unwind : "$documents" },
... // match for elements, "documents" is no longer an array
... { $match: { "documents.x" : 1 } },
... // re-create documents array
... { $group : { _id : "$_id", documents : { $addToSet : "$documents" } }}
... ]);
{
"result" : [
{
"_id" : ObjectId("515e2e6657a0887a97cc8d1a"),
"documents" : [
{
"x" : 1,
"y" : 3
},
{
"x" : 1,
"y" : 2
}
]
}
],
"ok" : 1
}
有关aggregate() 的更多信息,请参阅http://docs.mongodb.org/manual/applications/aggregation/
关于mongodb - 如何检索Mongodb中数组中存在的所有匹配元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429243/