I have a collection with documents like this one:
{
"_id" : "bc923adf-ddd9-4987-a759-2d3f8dbffe3e",
"title" : "DocumentTitle",
"nestedObjects" : [
{
"_id" : "3eef3a60-8d70-4640-b494-cb17e52e73a7",
"startTime" : "21:00:00",
"endTime" : "00:00:00"
},
{
"_id" : "5aa8ca60-8d70-4640-b494-cb17e52e4caa",
"startTime" : "17:00:00",
"endTime" : "23:00:00"
}
]
}
I need a query to get the 'nestedObject' that matches both Ids, root object Id and nested object Id. For instance, given root object Id equals "bc923adf-ddd9-4987-a759-2d3f8dbffe3e" and nested object Id equals "5aa8ca60-8d70-4640-b494-cb17e52e4caa", I want to get this result:
{
"_id" : "5aa8ca60-8d70-4640-b494-cb17e52e4caa",
"startTime" : "17:00:00",
"endTime" : "23:00:00"
}
I tried with this query;
var nestedObject = db.myCollection.aggregate(
[
{ "$match" : { "_id" : "bc923adf-ddd9-4987-a759-2d3f8dbffe3e" } },
{ "$unwind" : "$nestedObjects" },
{ "$match" : { "nestedObjects._id" : "5aa8ca60-8d70-4640-b494-cb17e52e4caa" } },
{ "$project" : { "startTime" : "$nestedObjects.startTime", "endTime":"$nestedObjects.endTime" } }
]);
I expected to be able to access starTime
and endTime
properties using nestedObject.startTime
with no luck. Also, I'd like to get the whole nested object without the need of listing all its properties in the project
phase.
What am I doing wrong? Is there an easier query I could run?
Thanks.