![](/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.