繁体   English   中英

在聚合中嵌套在数组中的 object 中的字段上使用 MongoDB $split 运算符

[英]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" } }
])

这是解释:

  1. $unwind 将数组取出以便可以拆分
  2. 使用 $project 和 $split 拆分字符串
  3. $group 将它们缝合在一起
  4. $project 以修复所需 output 中的文档形状

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM