mongodb在聚合期间重命名对象内的键

时间:2017-03-13 08:54:37

标签: mongodb aggregation-framework

我有一个mongodb聚合查询

return this.collection.aggregate([
    { $match: { _id: ObjectID(locationId) } },
    {
        $lookup:{
            from: "buildings",
            localField: "userId",
            foreignField: "ownerId",
            as: "areas"
        }
    },
    {
        $project: {     
            "location_id": "$_id",
            "locationName": "$locationName", 
            "areas": "$areas"
        }
    }
]).toArray();

其中areas字段是对象数组

[{
  key: value
}]

是否可以在聚合过程中重命名此密钥?

2 个答案:

答案 0 :(得分:0)

是的,您可以unwind - group您的区域如下:

return this.collection.aggregate([
            { $match: { _id: ObjectID(locationId) } },
            {
               $lookup:
                 {
                   from: "buildings",
                   localField: "userId",
                   foreignField: "ownerId",
                   as: "areas"
                 }
            },
            {
                $project: {     "location_id": "$_id",
                                "locationName": "$locationName", 
                                "areas": "$areas"
                          }
            },
            {
                $unwind: "$areas"
            },
            {
                $group: {   "_id": {"location_id": "$_id", "locationName": "$locationName"}, 
                            "areas": {$push: {new_key: "$areas.key"}} //<== renaming 'key' to 'new_key'
                        }
            },
            {
                $project: {     "_id": 0,
                                "location_id": "$_id.location_id",
                                "locationName": "$_id.locationName", 
                                "areas": "$areas"
                          }
            }
        ]).toArray();

答案 1 :(得分:0)

,但可能不像您预期​​的那么容易。

首先,您需要使用$unwind来获取每个区域的文档。 <{1}}具有相同位置的文档(因此同一$group)重新组合在一起。

_id实际上也做了投射。您可以使用$group中的$first来选择未展开的字段。

您尚未告知区域对象的属性。在示例中,我假设它具有$groupcoords属性。

shape

请注意,您最终会收到额外的return this.collection.aggregate([ { $match: { _id: ObjectID(locationId) } }, { $lookup:{ from: "buildings", localField: "userId", foreignField: "ownerId", as: "areas" } }, { $unwind: "$areas" }, { $group: { "_id": "$_id", "location_id": { $first: "$_id" }, "locationName": { $first: "$locationName" }, "areas": { $push: { "latitude": "$coords.lat", "longitude": "$coords.lon", "shape": "$shape" } } } } ]).toArray(); 字段(可能会被忽略),因为_id需要$group