简体   繁体   中英

MongoDB Java Driver aggregation with regex filter

I am using MongoDB Java Driver 3.6.3. I want to create regex query with group by aggregation to retrieve distinct values.

Let's say I have json:

[{
  "name": "John Snow",
  "category": 1
},
{
  "name": "Jason Statham",
  "category": 2
},
{
  "name": "John Lennon",
  "category": 2
},
{
  "name": "John Snow",
  "category": 3
}]

I want to create query where regex is like "John.*" and group it by name so there would be only one "John Snow"

Expected result is:

[{
  "name": "John Snow",
  "category": 1
},
{
  "name": "John Lennon",
  "category": 2
}]

The answer provided by felix is correct, in terms of Mongo Shell commands. The equivalent expression of that command using the MongoDB Java driver is:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");

AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(

    // Java equivalent of the $match stage
    Aggregates.match(Filters.regex("name", "John")),

    // Java equivalent of the $group stage
    Aggregates.group("$name", Accumulators.first("category", "$category"))

));

for (Document document : documents) {
    System.out.println(document.toJson());
}

The above code will print out:

{ "_id" : "John Lennon", "category" : 2 }  
{ "_id" : "John Snow", "category" : 1 }  

You can achieve this with a $regex in $match stage, followed by a $group stage:

db.collection.aggregate([{
    "$match": {
        "name": {
            "$regex": "john",
            "$options": "i"
        }
    }
}, {
    "$group": {
        "_id": "$name",
        "category": {
            "$first": "$category"
        }
    }
}])

output:

[
  {
    "_id": "John Lennon",
    "category": 2
  },
  {
    "_id": "John Snow",
    "category": 1
  }
]

you can try it here: mongoplayground.net/p/evw6DP_574r

You can use Spring Data Mongo

like this

    Aggregation agg = Aggregation.newAggregation(
        ggregation.match(ctr.orOperator(Criteria.where("name").regex("john", "i")),
                Aggregation.group("name", "category")
        );
          AggregationResults<CatalogNoArray> aggResults = mongoTemp.aggregate(agg, "demo",demo.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM