Search code examples
mongodbaggregation-frameworkmongo-javamongo-java-driver

Not able to get the aggregate result in mongo embedded document by querying


Issue in querying the embedded document in mongo db. I am trying to get the conversationId for the users but it returning null.

Sample document:

{
"_id" : ObjectId("5787391f191fda3a4430c749"),
"conversationId" : "fWFGIr0xAbQytmVcQIPV",
"user" : [{_id : "800", "name" : "Tim"},{_id : "500", "name" : "Kingsley"},
{_id : "400", "name" : "Roger"}],
"type" : "PRIVATE"
}

Query:

Aggregation agg = newAggregation(
            match(Criteria.where("type").is("PRIVATE")),
            group("conversationId").push("user.id").as("users"),
            match(Criteria.where("users").all(Arrays.asList('800','400','500')))
            );
    AggregationResults<Rooms> groupResults = mongoOps.aggregate(agg, ROOMS, Rooms.class);
      List<Rooms> result = groupResults.getMappedResults();
      result.get(0).getId() // returns null

The result.get(0).getId() is returning null, as per my query I am expecting the conversation Id that is present for the users.


Solution

  • I am not sure, why you are grouping on conversationId and then creating a set with user's id who took part in that conversation.

    If your desired result is to find a conversation in which the users '800', '400' and '500', then you can straight away use find query with $all.

    Mongo Query will look like this:

    db.test.find({"user._id":{"$all":["800","500","400"]}})