在mongoDB中的另一个数组中查询整个特定数组
我有一个mongoDB集合,称为myCollection,在myCollection内部有一个如下结构:在mongoDB中的另一个数组中查询整个特定数组,mongodb,Mongodb,我有一个mongoDB集合,称为myCollection,在myCollection内部有一个如下结构: { "id": 1234, "posts": [ [ { "id": "0.0", "name": "john", "message": "hello" }, { "id": "0.1",
{
"id": 1234,
"posts": [
[
{
"id": "0.0",
"name": "john",
"message": "hello"
},
{
"id": "0.1",
"name": "jane",
"message": "good morning"
},
{
"id": "0.2",
"name": "josh",
"message": "good evening"
}
],
[
{
"id": "1.0",
"name": "mark",
"message": "good lunch"
}
],
[
{
"id": "2.0",
"name": "john",
"message": "bye bye"
},
{
"id": "2.1",
"name": "mark",
"message": "hi"
}
]
]
}
谁能告诉我如何查询此结构以获取包含特定对象的整个数组?
例如,围绕此特定对象启动查询:
{
"id": "2.0",
"name": "john",
"message": "bye bye"
}
我希望获得整个阵列:
[
{
"id": "2.0",
"name": "john",
"message": "bye bye"
},
{
"id": "2.1",
"name": "mark",
"message": "hi"
}
]
希望以下查询对您有所帮助:
db.myCollection.aggregate([
{ $match : { "id": 1234}},
{ $unwind : '$posts'},
{$match : {
'posts' : { $elemMatch : { 'id' : '2.0',name : 'john'}}
}
},
{ $unwind : '$posts'},
{ $project : {
'id' : '$posts.id',
name : '$posts.name',
message :'$posts.message',
_id : 0
}
}
])
谢谢你的回复!myCollection还包含除id为“1234”的文档之外的其他文档。那么,我如何在查询中指定您建议我搜索的数组,该数组只在id为“1234”的文档中包含{id':'2.0',name:'john'}对象?答案已更新!检查您是否通过“1234”或1234。非常感谢您的回答。不幸的是,它不起作用(查询不返回数组[{“id”:“2.0”,“name”:“john”,“message”:“bye-bye”},{“id”:“2.1”,“name”:“mark”,“message”:“hi”}]…:(特别是,使用您建议的查询,我检索集合中的整个结构。您能告诉我如何仅获取整个数组[{“id”:“2.0”,“name”:“john,“message”:“bye bye”},{“id”:“2.1”,“name”:“mark”,“message”:“hi”}]?非常感谢@the_mahasagar对您的帮助。您的解决方案工作正常,正是我所需要的!