【问题标题】:Using MongoDB $split operator on field in object nested in array in aggregation在聚合中嵌套在数组中的对象中的字段上使用 MongoDB $split 运算符
【发布时间】:2020-11-14 03:49:39
【问题描述】:

我有一个这样的 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/) 中发现“嵌套字段时,不能在嵌入文档中使用点表示法来指定字段,例如 contact: { "address.country": } 无效。”。所以我的猜测是做不到的。至少不像我在尝试。我试图用 $map 或 $filter 运算符绕过它,但显然没有成功。请帮忙。

【问题讨论】:

    标签: mongodb split aggregation projection


    【解决方案1】:

    以下查询有效,但可能不是最快/最简洁的解决方案:

    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 修复所需输出中文档的形状

    【讨论】:

    • 效果很好,正是我需要的,谢谢,但我不敢相信它不能像我在我的问题中尝试的那样完成。像这样在聚合中增加 4 个额外步骤似乎适得其反。
    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 2018-09-10
    • 2021-08-13
    • 2016-01-18
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多