如何检索子文档数组中的所有文档,如果有任何重复的字段如何检索最新的文档?

时间:2014-05-17 08:49:54

标签: mongodb duplicates subdocument

我的db结构如下所示。

{
    "_id": ObjectId("53770b9de4b0ba6f4c976a27"),
    "source": [{
        "value": 5127,
        "createdAt": ISODate("2014-05-7T07:11:00Z"),
        "generated": ISODate("2014-05-17T07:23:00Z"),
    }, {
        "value": 5187,
        "createdAt": ISODate("2014-05-17T07:39:00Z"),
        "generated": ISODate("2014-05-17T07:40:00Z"),
    }, {
        "value": 5187,
        "createdAt": ISODate("2014-05-17T07:39:00Z"),
        "generated": ISODate("2014-05-17T07:41:00Z")
    }],
}

在这个子文档数组中有一个副本。我需要编写mongo db查询来检索所有子文档,如果有任何重复,那么基于"生成" 价值我需要像下面这样重新获得最新信息。

{
    "_id": ObjectId("53770b9de4b0ba6f4c976a27"),
    "source": [{
        "value": 5127,
        "createdAt": ISODate("2014-05-17T07:11:00Z"),
    }, {
        "value": 5187,
        "createdAt": ISODate("2014-05-17T07:39:00Z"),
        "generated": ISODate("2014-05-17T07:41:00Z")

    }],

}

有没有办法获取数据,比如使用mongo db query?

1 个答案:

答案 0 :(得分:0)

使用aggregation framework,您可以完成这项工作。

db.test.aggregate([
    {$unwind: '$source'},
    {$group: {_id: {value: "$source.value", createdAt: "$source.createdAt"}, generated: {$max: "$source.generated"}}}
]);

这会给你结果:

{ "_id" : { "value" : 5187, "createdAt" : ISODate("2014-05-17T07:39:00Z") }, "generated" : ISODate("2014-05-17T07:41:00Z") }
{ "_id" : { "value" : 5127, "createdAt" : ISODate("2014-05-07T07:11:00Z") }, "generated" : ISODate("2014-05-17T07:23:00Z") }

与你想要的有点不同。但如果你真的想要上面的格式,试试这个:

db.test.aggregate([
    {$unwind: '$source'},
    {$group: {_id: {_id: "$_id", value: "$source.value", createdAt: "$source.createdAt"}, generated: {$max: "$source.generated"}}},
    {$group: {_id: "$_id._id", source: {$push: {value: "$_id.value", createdAt: "$_id.createdAt", generated: "$generated"}}}}
]);

给你:

{
    "_id": ObjectId("53770b9de4b0ba6f4c976a27"),
    "source": [{
        "value": 5187,
        "createdAt": ISODate("2014-05-17T07:39:00Z"),
        "generated": ISODate("2014-05-17T07:41:00Z")
    }, {
        "value": 5127,
        "createdAt": ISODate("2014-05-07T07:11:00Z"),
        "generated": ISODate("2014-05-17T07:23:00Z")
    }]
}