I'd like to combine these data, this two data has the same root _id, and video field has the same songs._id value. Finally, I want to merge this video datas that has same song._id to array of video under same songs data and same root i mean,
[
{
"_id": ObjectId("5e328f15b7e4937f52c67679"),
"name": "HoYoung",
"like": 0,
"view": 0,
"songs": {
"_id": "32f3156c-ed37-40dc-af96-dcbf53a84a58",
"name": "testName",
"lyrics": "testLyrics",
"like": 0,
"video": {
"_id": "1255c77b-f3f6-466a-bd1a-0124555e5592",
"like": 0,
"view": 0
}
}
},
{
"_id": ObjectId("5e328f15b7e4937f52c67679"),
"name": "HoYoung",
"like": 0,
"view": 0,
"songs": {
"_id": "32f3156c-ed37-40dc-af96-dcbf53a84a58",
"lyrics": "testLyrics",
"like": 0,
"name": "testName",
"video": {
"_id": "f08a433a-e120-459f-8bf1-1f55081dbf82",
"like": 0,
"view": 0
}
}
}
]
to
{
"_id" : ObjectId("5e328f15b7e4937f52c67679"),
"name" : "HoYoung",
"like" : 0
"songs" : {
"_id" : "32f3156c-ed37-40dc-af96-dcbf53a84a58",
"name" : "testName",
"lyrics" : "testLyrics",
"like" : 0,
"view" : 0,
"video" : [{
"_id" : "1255c77b-f3f6-466a-bd1a-0124555e5592",
"like" : 0,
"view" : 0
},{
"_id" : "f08a433a-e120-459f-8bf1-1f55081dbf82",
"like" : 0,
"view" : 0
}]
}
}
How can i do this? group? problem is i cannot do grouping subdocument of subdocument
You need to $group
by songs._id
(and root _id
in your context) and accumulate video
sub-document inside a temporal video
array (we store inside root
top level document to merge in the next stage).
db.collection.aggregate([
{
$group: {
_id: "$songs._id",
root: {
$first: "$$ROOT"
},
video: {
$push: "$songs.video"
}
}
},
{
$project: {
name: "$root.name",
like: "$root.like",
songs: {
_id: "$root.songs._id",
name: "$root.songs.name",
lyrics: "$root.songs.lyrics",
like: "$root.songs.like",
view: "$root.songs.view",
video: "$video"
}
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.