根据密码合并商店详细信息

时间:2018-11-30 02:36:34

标签: mongodb

我有一个mongodb集合“ test”,其中包含商店数据。下面显示了两个文档-

{
    "_id" : ObjectId("5bfffd884c90a040bab5e35a"),
    "facilityCode" : "ST99",
    "area" : "Bokaro",
    "landmark" : "Vivira Mall",
    "storeContact" : NumberLong(06542233443),
    "pinCode" : 827004,
    "Status" : "Active"
}

/* 2 */
{
    "_id" : ObjectId("5bfffd884c90a040bab5e35b"),
    "facilityCode" : "ST100",
    "area" : "Bokaro",
    "landmark" : "Opera Mall",
    "storeContact" : NumberLong(9909090909),
    "pinCode" : 827004,
    "Status" : "InActive"
}

在固定的pincode上可能有多个商店(一对多关系)。我希望所有按垂直密码输入的存储都在一个文档中,例如bolow-

{
    "pincode" : 827004,
    "storeDetail" : [ 
        {
            "landmark" : "Vivira Mall",
            "facilityCode" : "ST99",
            "area" : "Bokaro",
            "storeContact" : "06542233443",
            "priority" : 0,
            "Status" : "Active"
        },
        {
            "landmark" : "Opera Mall",
            "facilityCode" : "ST100",
            "area" : "Bokaro",
            "storeContact" : "9909090909",
            "priority" : 0,
            "Status" : "InActive"
        }
    ]
}

所有优先级都可以设置为零。谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用聚合并将它们分组,如下所示:

Collection.aggregate([
{$group: {_id: '$pinCode'}, storeDetail: {
    $push: {
        landmark: '$landmark',
        facilityCode: '$facilityCode',
        area: '$area',
        storeContact: '$storeContact',
        priority: 0,
        Status: '$Status'
    }
}},
{$project: {pincode: '$_id', storeDetail: 1}}

])