1

I have this type of document into my collection. I store many components which have a version.

{
   "_id" : "compagny/component_name/2.3.3",
   "type" : "action",
   "owner" : "compagny",
   "name" : "component_name",
   "version" : "2.3.3",
   "splitVersion" : {
      "major" : 2,
      "minor" : 3,
      "patch" : 3 },
    "jar" : "url...myArtifact.jar",
    "timestamp" : ISODate("2014-10-16T14:25:22.954Z"),
    "artifactKey" : "artifact-loadsupport/2.3.3"

}

I am searching a way to retrieve the latest version of a component. In other word, get the latest version of every components that have the same owner/name.

I can have my result with this agregation but the result is not well formated :

db.components.aggregate(   
{$sort: {type : 1, owner : 1, name : 1, "splitVersion.major" : -1, "splitVersion.minor": -1, "splitVersion.patch" : -1} },   
{$group: { _id: {owner:"$owner", name : "$name"}, version: { $first: "$version" }}}
)

I can have my result whith this aggregate but how can I have the complete document returned ? (the same like .find())

Because I map my data with Jongo, it is not easy to deal with this aggregate result...The result no map with my document class. I have to bind manually earch value...

Thanks

ascott
  • 552
  • 1
  • 5
  • 16

1 Answers1

1

You can use what is suggested here https://stackoverflow.com/a/16662878/1333610 with $project to do this.

db.components.aggregate(   
{ $sort: {type : 1, 
          owner : 1, 
          name : 1, 
          "splitVersion.major" : -1, 
          "splitVersion.minor": -1, 
          "splitVersion.patch" : -1
         } 
},
{$group: { _id: {owner:"$owner", name : "$name"}, 
            version: { $first: "$version" },
            splitVersion: { $first: "$splitVersion" },
            jar: { $first: "$jar" }
            // similarly add all the fields in your doc with $first
          }
},
{$project: {_id: 0, 
             owner: "$_id.owner", 
             name: "$_id.name", 
             version: 1, 
             splitVersion: 1, 
             jar: 1
             // add all the fields you want here
            } 
}
)

This works because $first stores the fields that correspond with the first match of the first field i.e. version in your case.

Community
  • 1
  • 1
arun
  • 10,685
  • 6
  • 59
  • 81