假设我有以下文件:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
},
{
"_id":"5bd7a9d2604b760004947833",
"shape":"circle",
"colors": []
}
]
},
{
"_id":"5bd5ba2ca677cb000469168a",
"shapes":[
{
"_id":"5bd7a9e4604b760004947834",
"shape":"square",
"colors": []
},
{
"_id":"5bd6d697975e892464b0ed31",
"shape":"circle",
"colors": []
}
]
}
通过使用以下代码:
db.test.aggregate(
{ $match : {
"shapes.shape": "square"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes.shape": "square"
}}
)
它给了我这个结果:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
},
{
"_id":"5bd5ba2ca677cb000469168a",
"shapes":[
{
"_id":"5bd7a9e4604b760004947834",
"shape":"square",
"colors": []
}
]
}
但是我想要得到的只是第一个看起来像这样的文档:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
}
因此,我尝试在子文档中使用“ _id”属性,如下所示:
db.test.aggregate(
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}}
)
但是这样做会返回一个空数组,就像这样:
[]
基本上,我想要在查询中使用特定子文档的“ _id”属性,以便可以将某些内容推入该特定子文档的“ colors”数组。我应该如何更改我的查询语句以使我能够使用“ _id”属性?
答案 0 :(得分:0)
已解决
此问题由@AnthonyWinzlet在上面的第二条评论解决。