1

I'm new on MongoDB, on my project i'm saving any change on specific document creating a new document with changes and a version field increased.

Example:

{_id:"X", number : "1", firstname : "John", lastname : "Sand", version : "1"}
{_id:"Y", number : "1", firstname : "John", lastname : "Snow", version : "2"}
{_id:"Z", number : "2", firstname : "Cersei", lastname : "Lannister", version: "1"}

When I have to show data i should get the last version of document distincted by field "number"

the result expected is:

{_id:"Y", number : "1", firstname : "John", lastname : "Snow", version : "2"}
{_id:"Z", number : "2", firstname : "Cersei", lastname : "Lannister", version: "1"}

Is there a method to do this with one query? I'm looking for aggregation but the subject is very dispersive.

1 Answers1

2

If the number element is an entity identifier, then you can use the aggregation.

At first, you need to sort documents by the version value.

Then you need to group documents by the number value and take values of the first document from the group.

And finally, you need to format the data output.

Example:

db.getCollection('collection_name').aggregate([
    {
        $sort: {'version': -1}
    },
    {
        $group: {
            _id: "$number",
            original_id: {$first: "$_id"},
            firstname: {$first: "$firstname"},
            lastname: {$first: "$lastname"},
            version: {$first: "$version"},
        }
    },
    {
        $project: {
            _id: "$original_id",
            number: "$_id",
            firstname: 1,
            lastname: 1,
            version: 1
        }
    }
])
Neodan
  • 5,154
  • 2
  • 27
  • 38