Skip to content

Instantly share code, notes, and snippets.

@usametov
Last active May 29, 2023 01:39
Show Gist options
  • Save usametov/2aa98d5d66bf1d650f3032691cadf0f8 to your computer and use it in GitHub Desktop.
Save usametov/2aa98d5d66bf1d650f3032691cadf0f8 to your computer and use it in GitHub Desktop.
//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 }
@Ichi-1
Copy link

Ichi-1 commented Sep 2, 2022

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