Query for latest version of a document by date in mongoDB

血红的双手。 提交于 2019-12-05 23:54:09

If I understand the question correctly you could use something like this

db.getCollection('yourTransactionsCollection').aggregate([
    {
        $sort: {
            "transaction_reference": 1,
            "object_creation_date": -1
        }
    },
    {
        $group: {
            _id: "$transaction_reference",
            "transaction_date": { $first: "$transaction_date" },
            "object_creation_date": { $first: "$transaction_date" },
            "transaction_sale_value": { $first: "$transaction_sale_value" }
        }
    }
])

which outputs a result like the following

{
    "_id" : "SI-1",
    "transaction_date" : "2016-06-16T00:00:00.201Z",
    "object_creation_date" : "2016-06-16T00:00:00.201Z",
    "transaction_sale_value" : null
}

Note that you can change the $sort to just include the object_creation_date but I included both transaction_reference and object_creation_date as I think it would make sense to create a composite index on both of them instead of just the creation date. Adjust that according to your indexes so that the $sort will hit one.
In addition there was no document field transaction_sale_value hence the null for it in the result. Maybe you missed that or it is just not in your sample documents but I think you get the idea and can adjust it to your needs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!