使用mongo

时间:2016-06-01 09:13:43

标签: mongodb pymongo

我有以下格式的mongo文档。我想获取每个唯一phone_numbers的devices_ids,但我的mongo查询没有给出正确的结果。

有人可以指出我的问题吗?

{
    "_id" : ObjectId("56cf21562e7b232d022f334e871"),
    "uid" : 5,
    "device_id" : "352136234234325",
    "name" : "user1",
    "email" : ["user1@mail.com" ],
    "phone_number" : [
        "+919890273451"
    ]
}
{
    "_id" : ObjectId("56cf21562e7b2d032422f334e872"),
    "uid" : 15,
    "device_id" : "3521360123444",
    "name" : "user1",
    "email" : [ "user1@mail.com"],
    "phone_number" : [
        "+919890273451"
    ]
}
{
    "_id" : ObjectId("56cf21562342e7b2d022f334e873"),
    "uid" : 51,
    "device_id" : "352136067208559",
    "name" : "user1",
    "email" : [ "user1@mail.com"],
    "phone_number" : [
        "+919890273451"
    ]
}

我的预期输出是

{
"phone_number" : "+919890273451",
device_ids : ["352136067208559","3521360123444","352136234234325"]}
}

我试过这个问题:

db.contact.aggregate([{
    $unwind: "$phone_number"
},
{$group: {"_id":"$phone_number"},
device_ids: { $push:  { user: "$device_id"} }
}
], {
allowDiskUse:true,
cursor:{}
});

1 个答案:

答案 0 :(得分:1)

使用$push时,您不需要指定名称 - 只需按普通值即可。

请参阅以下内容:

db.coll.aggregate([{
        $unwind : "$phone_number"
    }, {
        $group : {
            _id : "$phone_number",
            device_ids : {
                $addToSet : "$device_id"
            }
        }
    }
])