0

我有下面这样的数据库结构。

{
    "_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 查询一样获取数据?

4

1 回答 1

0

使用聚合框架,您可以完成这项工作。

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")
    }]
}
于 2014-05-17T09:49:32.727 回答