Suppose I have the following documents:
{
"_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": []
}
]
}
By using this code:
db.test.aggregate(
{ $match : {
"shapes.shape": "square"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes.shape": "square"
}}
)
It gives me this result:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
},
{
"_id":"5bd5ba2ca677cb000469168a",
"shapes":[
{
"_id":"5bd7a9e4604b760004947834",
"shape":"square",
"colors": []
}
]
}
But what I want is to get only the first document that would look like this:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
}
So I tried to use the "_id" property in the subdocument like this:
db.test.aggregate(
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}}
)
But by doing that it would return me an empty array just like this:
[]
Basically what I want is to use the "_id" property of a specific sub-document in my query so that I can push something on the "colors" array of that specific sub-document. How should I change my query statement that I will be able to use the "_id" property?