I am trying to use aggregate to get latest and complete document , but my subDocument is not incomplete.
this is my document list example.
[
{
"t": {
"$date": "2021-01-01T00:00:01.000Z"
},
"id": "1234",
"a": {
"y": "y1",
"x": "x1"
},
"b": {
"c": "c1",
"d": {
"dd":"dd1"
}
}
},
{
"t": {
"$date": "2021-01-01T00:00:02.000Z"
},
"id": "1234",
"a": {
"y": "y2"
},
"b": {
"c": "c1",
"d": {
"ee":"ee1"
}
}
},
{
"t": {
"$date": "2021-01-01T00:00:03.000Z"
},
"id": "1234",
"b": {
"d": {
"ee":"ee2"
}
}
]
And I expected result is
[{
"id": "1234",
"a": {
"x": "x1",
"y": "y2"
},
"b": {
"c": "c1",
"d": {
"dd":"dd1" ,
"ee":"ee2"
}
}
}]
So I try to use aggregate like this
db.collection.aggregate([
{
$sort: {
"t": 1
}
},
{
$match: {
"id": "1234"
}
},
{
$group: {
_id: null,
result: {
$mergeObjects: "$$ROOT"
}
}
}
])
But actual result is this , because aggregate just get first level keys.
[
{
"_id": null,
"result": {
"_id": ObjectId("5a934e000102030405000002"),
"a": {
"y": "y2"
},
"b": {
"d": {
"ee": "ee2"
}
},
"id": "1234",
"t": ISODate("2021-01-01T00:00:03Z")
}
}
]
So How to meet my expectations?
I have no idea.
Thanks!!