Search code examples
springmongodbspring-datacriteriaspring-data-mongodb

Find an object with biggest semver version


Let's say I have some documents in MongoDB with a version property(semver version), for example something like { ..., version: { major: 1, minor: 2, patch: 13 } }, or { ..., version: "1.2.13" }, i haven't decided yet which format i will be using.

I need to find the document with the highest version.
For example, if collection has two documents with {..., version: "0.10.0"} and {..., version: "1.0.0"} then i would like to get document with version = "1.0.0"

I'm using Spring Data MongoDB, so ideally i would like to find some solution by using Criteria API


Solution

  • It turned out to be quite simple when i use first format of version:
    { ..., version: { major: 1, minor: 2, patch: 13 } }

    Then i can just sort by all those three fields and take the one top document:

    db.metadata.find({})
       .projection({})
       .sort({ "version.major": -1, "version.minor": -1, "version.patch": -1 })
       .limit(1)
    

    This query is written by using Criteria API:

    public Metadata getLatestMetadata() {
        Criteria criteria = Criteria
                .where("type").is(TEST_TYPE);
    
        Query query = Query.query(criteria).with(getVersionSort()).limit(1);
        return mongoOperations.findOne(query, Metadata.class);
    }
    
    private Sort getVersionSort() {
        return Sort.by(new Sort.Order(Sort.Direction.DESC, "version.major"),
                new Sort.Order(Sort.Direction.DESC, "version.minor"),
                new Sort.Order(Sort.Direction.DESC, "version.patch"));
    }