![](/img/trans.png)
[英]Merging nested object fields into a single nested array field in MongoDB Aggregation
[英]Using MongoDB $split operator on field in object nested in array in aggregation
我有一個像這樣的 MongoDB 文檔:
{
"_id" : ObjectId("5c949609ff5e3d6119758730"),
"product_name" : "Shoes",
"field_to_split" : "one##two##three##four",
"assets" : [
{
"url" : "www.blabla.com/1",
"nested_field_to_split" : "one##two##three##four"
},
{
"url" : "www.blabla.com/2",
"nested_field_to_split" : "one##two##three##four"
},
{
"url" : "www.blabla.com/3",
"nested_field_to_split" : "one##two##three##four"
},
{
"url" : "www.blabla.com/4",
"nested_field_to_split" : "one##two##three##four"
}
]}
我想把它變成這樣:
{
"_id" : ObjectId("5c949609ff5e3d6119758730"),
"product_name" : "Shoes",
"field_to_split" : "one##two##three##four",
"assets" : [
{
"url" : "www.blabla.com/1",
"nested_field_to_split" : ['one', 'two', 'three', 'four']
},
{
"url" : "www.blabla.com/2",
"nested_field_to_split" : ['one', 'two', 'three', 'four']
},
{
"url" : "www.blabla.com/3",
"nested_field_to_split" : ['one', 'two', 'three', 'four']
},
{
"url" : "www.blabla.com/4",
"nested_field_to_split" : ['one', 'two', 'three', 'four']
}
]}
這必須在聚合期間完成。 我試圖這樣做:
{ "$project":{
"assets.nested_field_to_split":{
"$split":[
"$assets.nested_field_to_split",
"##"
]
}
}
}
我在文檔( https://docs.mongodb.com/manual/reference/operator/aggregation/project/ )中發現“嵌套字段時,不能在嵌入文檔中使用點符號來指定字段,例如聯系人:{“address.country”:<1 或 0 或表達式>} 無效。”。 所以我的猜測是做不到的。 至少不像我在嘗試。 我試圖用 $map 或 $filter 運算符圍繞它 go ,但顯然沒有成功。 請幫忙。
以下查詢有效,但可能不是最快/最簡潔的解決方案:
db.t.aggregate([
{ $unwind: "$assets" },
{ $project : { "product_name": "$product_name", "field_to_split" :"$field_to_split", "assets_url": "$assets.url", "assets_split" : { $split: ["$assets.nested_field_to_split", "##"] } } },
{ $group : { _id: { _id: "$_id", "product_name": "$product_name", "field_to_split" : "$field_to_split" }, "assets": { $push: { "url": "$assets_url", "nested_field_to_split": "$assets_split" } } } },
{ $project: { _id: "$_id._id", "product_name": "$_id.product_name", "field_to_split" : "$_id.field_to_split", "assets": "$assets" } }
])
這是解釋:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.