【问题标题】:Document Tracking, Mongodb query for latest document state文档跟踪,MongoDB 查询最新文档状态
【发布时间】:2018-02-03 05:11:06
【问题描述】:

这适用于文档跟踪/管理系统,系统将跟踪文档的状态。文档状态包括“enrolled”、“endorsed”、“untracked”等...在我的mongodb中,每个文档状态更改都会在mongodb中有一个条目..

以下是文档状态的示例集合:

[//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
    },
]

使用聚合,我可以查询文档更改时的最新日期(“时间”字段),但我不知道如何包含文档的实际状态,例如“已注册”、“未跟踪”等。

【问题讨论】:

    标签: json mongodb


    【解决方案1】:

    $sortwhen 的文档按降序排列,$group 的文档按降序排列并从中获取$first 状态

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

    或按升序排序并取最后一个状态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2021-02-25
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多