在MongoDB查询中将单个数组字段转换为对象

时间:2020-04-15 07:29:24

标签: mongodb mongodb-query aggregation-framework lookup

下面是我的查询,该查询在两个表上工作以获取数据

db.accounts.aggregate([
    {
        $lookup: {
            from: 'accounts_destinations',
            localField: "_id",
            foreignField: "acc_Dest_id",
            as: "accountDestinationDetails"
         },
     },
  {
    $group: {
      _id: "$type",
      record: {
           $push:  {_id: "$_id", description: "$description" , costing: "$accountDestinationDetails.costing"}
       }
    }
  },
  {
    "$group": {
      "_id": null,
      "data": {
        "$push": {
          "k": {
            $toString: "$_id"
          },
          "v": "$record"
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": "$data"
      }
    }
  }
])

这里,我遇到的问题是 accountDestinationDetails.costing 作为 Array 返回,而我希望将其作为普通对象。

//上述查询的输出

{
    "domestic" : [ 
        {
            "_id" : ObjectId("2s05fea52f804ab99b12e7c0"),
            "description" : "Domestic account with local mapping",
            "costing" : [ 
                35
            ]
        }, 
        {
            "_id" : ObjectId("2s05aet52f740ab99b12f6h0"),
            "description" : "Domestic account with non mapping",
            "costing" : []
        }
    ],
    "international" : [ 
       {
            "_id" : ObjectId("2s05tqz32f740fr00b12f6h0"),
            "description" : "International account with local mapping",
            "costing" : []
        }
    ]
}

这里唯一的问题是 costing 字段以数组的形式出现(costing [],costing [35])。

我尝试过的事情

我试图像下面那样展开成本核算字段

 {$unwind: "$accountDestinationDetails.costing"} 

但是它打乱了联接,我只获得了具有映射的记录,而不是 LEFT联接。下面是如果我使用unwind的输出

{
        "domestic" : [ 
            {
                "_id" : ObjectId("2s05fea52f804ab99b12e7c0"),
                "description" : "Domestic account with local mapping",
                "costing" : [ 
                    35
                ]
            }
        ],
}

0 个答案:

没有答案