Last active
May 29, 2023 01:39
-
-
Save usametov/2aa98d5d66bf1d650f3032691cadf0f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//here is document with NESTED Array | |
{ | |
"_id": "xyz-800", | |
"site": "xyz", | |
"user": 800, | |
"timepoints": [ | |
{"timepoint": 0, "a": 1500, "b": 700}, | |
{"timepoint": 2, "a": 1000, "b": 200}, | |
{"timepoint": 4, "a": 3500, "b": 1500} | |
] | |
} | |
/** | |
Starting MongoDb 3.4, we can use $addFields to add the top level fields | |
to the embedded document and use $replaceRoot to promote | |
embedded document to top level. | |
*/ | |
db.records.aggregate({ | |
$unwind: "$timepoints" | |
}, { | |
$addFields: { | |
"timepoints._id": "$_id", | |
"timepoints.site": "$site", | |
"timepoints.user": "$user" | |
} | |
}, { | |
$replaceRoot: { | |
newRoot: "$timepoints" | |
} | |
}) | |
// Sample Output | |
{ "timepoint" : 0, "a" : 1500, "b" : 700, "_id" : "xyz-800", "site" : "xyz", "user" : 800 } | |
{ "timepoint" : 2, "a" : 1000, "b" : 200, "_id" : "xyz-800", "site" : "xyz", "user" : 800 } | |
{ "timepoint" : 4, "a" : 3500, "b" : 1500, "_id" : "xyz-800", "site" : "xyz", "user" : 800 } |
This is incredibly helpful! Thanks for sharing!
You also can use $project in aggregation framework.
In this case it would be:
"$project": {
"_id": 1,
"site": 1,
"user": 1,
"timepoint": "$timepoints.timepoint",
"a": "$timepoints.a",
"b": "$timepoints.b",
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this one, saved my day 👍