2

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
}]

3 Answers 3

3

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 }  
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thanks. How to implement it in MongoDB Java Driver?
@Frido take a look at the documentation: mongo-java-driver/aggregation
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.