文档跟踪,Mongodb查询最新文档状态

时间:2018-02-03 05:11:07

标签: json mongodb

这适用于文档跟踪/管理系统,系统将跟踪文档的状态。文件状态包括"注册","背书","未跟踪"等等...在我的mongodb中,每个文档状态更改都会在mongodb中有一个条目..

以下是doc状态的示例集合:

[//FOR DOCUMENT ONE
    {
        "document": "doc1",
        "stateName": "enrolled",
        "when": ISODate("a date when the doc state changed")
    },
    {
        "document": "doc1",
        "stateName": "mark-for-review",
        "when": ISODate("a date when the doc state changed")
    },
    {
        "document": "doc1",
        "stateName": "endorsed",
        "when": ISODate("a date when the doc state changed")
    },
    //FOR DOCUMENT TWO
    {
        "document": "doc2",
        "stateName": "endorsed",
        "when": ISODate("a date when the doc state changed")
    },
    {
        "document": "doc2",
        "stateName": "untracked",
        "when": ISODate("a date when the doc state changed")
    }
]

现在我希望能够查询上述集合并获得如下结果:

[
    {
        "id" : "doc1",
        "state" : "endorsed"  // this should be based on the latest changed of the document1 from the 'when' column
    },
    {
        "id" : "doc2",
        "state" : "untracked" // this should be based on the latest changed of the document2 from the 'when' column
    },
]

使用聚合,我可以在文档发生变化时查询最新日期("当"字段),但我不知道如何包含文档的实际状态,例如"已注册&# 34;,"未跟踪"等等。

1 个答案:

答案 0 :(得分:0)

$sort when文档按降序排列,$group按文档排序,并从中获取$first

db.col.aggregate(
    [
        {$sort : {"when" : -1}},
        {$group : {_id : "$document", state : {$first : "$stateName"}}}
    ]
)

或按升序排序并采取最后状态