如何在 Mongodb 映射中创建对象

Bha*_*avi 2 mongodb pymongo mongodb-query aggregation-framework

我有一个如下所示的文档,我使用 mongo $map 来投影表内的字段并重命名键。$unwind由于某些内部复杂性,我无法使用。

{
"Table":[
    {"Lookup":{
        "CreatedBy":{
            "id": "User001",
            "Name":"UserName"
         }

        }
     }]
}
Run Code Online (Sandbox Code Playgroud)

我期望的输出看起来像这样

{
"Table":[
    {"Lookup":{
        "CreatedBy":"UserName"
        }
     }]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 mongo $map 来实现它,但不支持它

db.getCollection('TableDoc').aggregate([
        {
        "$project": {
            "Table": {
                "$map": {
                    "input": "$Table",
                    "in": {
                      "Lookup.CreatedAt": "$$this.Lookup.CreatedAt.Name",
                    }
                }               
             }
         }
        }
])
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以在不使用 $unwind 的情况下实现此目的

Nei*_*unn 5

这是支持的$map,但只是不使用“虚线字段路径”。相反,您使用“绝对”对象结构:

collection.aggregate([
  { "$addFields": {
    "Table": {
      "$map": {
        "input": "$Table",
        "in": {
          "Lookup": {
            "CreatedBy": "$$this.Lookup.CreatedBy.Name"
          }
        }
      }
    }
  }}
])
Run Code Online (Sandbox Code Playgroud)

或者,如果对象中有很多字段,您可以$mergeObjects在支持的情况下使用:

collection.aggregate([
  { "$addFields": {
    "Table": {
      "$map": {
        "input": "$Table",
        "in": {
          "$mergeObjects": [
            "$$this",
            { 
              "Lookup": {
                "CreatedBy": "$$this.Lookup.CreatedBy.Name"
              }
            }
          ]
        }
      }
    }
  }}
])
Run Code Online (Sandbox Code Playgroud)

当示例显示的字段比问题中的示例显示的字段多时,这就更有意义了。