How to write the following mongo query in springboot?

query –

db.collection.find().sort({$natural: -1 }).limit(5)

I was basically finding the most recent documents in the collection. But how should I write this query in springboot?

Hi @Vartika_Malguri
Welcome to the community forum!

MongoDB Compass provides the feature to convert the MongoDB query to a specific programming language. Please refer to the following documentation

However, this would be the Java code:

/*
 * Requires the MongoDB Java Driver.
 * https://mongodb.github.io/mongo-java-driver
 */

Bson filter = new Document();
Bson sort = new Document("$natural", -1L);

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
        "mongodb+srv://m001-student:m001-mongodb-basics@sandbox.6yvnh.mongodb.net/test?authSource=admin&replicaSet=atlas-gbccyn-shard-0&readPreference=primary&ssl=true"
    )
);
MongoDatabase database = mongoClient.getDatabase("sample_analytics");
MongoCollection<Document> collection = database.getCollection("accounts");
FindIterable<Document> result = collection.find(filter)
    .sort(sort)
    .limit((int)5L);

OR

    CriteriaDefinition filter = (CriteriaDefinition) new Document();
    List sort = (List) new Document("$natural", -1L);

    MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
        "mongodb+srv://m001-student:m001-mongodb-basics@sandbox.6yvnh.mongodb.net/test?authSource=admin&replicaSet=atlas-gbccyn-shard-0&readPreference=primary&ssl=true"
    )
);
    Query query = new Query().addCriteria(filter).with(Sort.by(sort));

Please note that $natural is “The order in which the database refers to documents on disk” (see [$natural]( https://www.mongodb.com/docs/manual/reference/glossary/#std-term-natural-order` ) ), thus it may not sort based on the most recent inserted documents. Realistically, you may be able to drop the natural sort criteria and receive the same ordering of documents. If it is feasible for you to modify the schema design to have a createdAtfield, thecreatedAt` field could be used to sort the data as per the requirements.

Also, would recommend you to visit the following documentation

PS: I would also recommend you to go through the following course
MongoDB Courses and Trainings | MongoDB University to understand and learn more on MongoDB with Java.

Let us know if you have any more doubts.

Thanks
Aasawari