[英]Mongodb subdocument fields union
我需要加入mongodb的兩個集合。 首先,我有一個像這樣的聚合:
db.messages.aggregate([
{
$lookup: {
from :"channels",
localField: "channels",
foreignField: "_id",
as: "merged_channels"
}
}
]).pretty()
整合之后,我的文檔如下所示:
{
"_id" : "21ca6117-1f14-4613-9407-db7f3a011142",
"author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
"title" : "test2",
"body" : "test2",
"channels" : [
"8008d5a8-eb3b-4e55-98c5-a60fd7275bd2",
"8008d5a8-eb3b-4e55-98c5-a60fd7275bd3"
],
"comments" : [
{
"author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
"body" : "comment1",
"created_at" : ISODate("2018-03-15T07:08:10.018Z")
},
{
"author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
"body" : "testbody",
"created_at" : ISODate("2018-03-15T07:08:09.366Z")
}
],
"created_at" : ISODate("2018-03-15T07:08:09.018Z"),
"updated_at" : ISODate("2018-03-15T07:08:09.366Z"),
"deleted_at" : null,
"merged_channels" : [
{
"_id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275bd2",
"author" : "03072fad-a8fd-53f3-b25f-abbfaf15b055",
"name" : "chan2",
"members" : [
{
"id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb5",
"type" : "group"
}
],
"created_at" : ISODate("2018-03-15T07:08:08.872Z"),
"updated_at" : ISODate("2018-03-15T07:08:08.872Z"),
"deleted_at" : null
},
{
"_id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275bd3",
"author" : "8008d5a8-eb3b-4e55-98c5-a60fd7275fg4",
"name" : "chan3",
"members" : [
{
"id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb5",
"type" : "group"
},
{
"id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb6",
"type" : "user"
},
{
"id" : "8008d5a8-eb3b-4e55-98c5-a60fd7275cb7",
"type" : "role"
}
],
"created_at" : ISODate("2018-03-15T07:08:08.872Z"),
"updated_at" : ISODate("2018-03-15T07:08:09.358Z"),
"deleted_at" : null
}
]
}
我想從chan2和chan3中獲取成員字段,將它們合並並放入根(消息)文檔中。 然后刪除merged_channels
字段。 刪除合並的字段不是問題,但不知道如何從子對象中提取字段並合並它們。
我將如何實現?
您可以在3.4中使用以下匯總。
$reduce
到$concatArrays
並投影,排除掉merged_channels字段。
db.col.aggregate({
"$addFields":{
"merged_arrays":{
"$reduce":{
"input":"$merged_channels",
"initialValue":[],
"in":{"$concatArrays":["$$value", "$$this.members"]}
}
}
},
{"$project":{"merged_channels":0}}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.