-
-
Save tanvirstreame/83711d8cc535b097cb78538fe5be8adc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great!