Home > OS >  How to write mongo query in springboot criteria
How to write mongo query in springboot criteria

Time:01-17

A little assistance on how to write this query in spring boot criteria.

db.collection.aggregate([
    {"$group" : { "_id": "$field1", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
])

CodePudding user response:

You can try this code:

GroupOperation group = Aggregation.group("field1").count().as("count");
MatchOperation match = Aggregation.match(Criteria.where("_id").ne(null).andOperator(Criteria.where("count").gt(1)));
ProjectionOperation project = Aggregation.project().andExpression("_id").as("name").andExclude("_id");

Aggregation aggregation = Aggregation.newAggregation(group, match, project);

mongoTemplate.aggregate(aggregation, "collection", YourClass.class);

Docs:

And a Baeldung example.

  • Related