0

I am working on writing aggregate queries using java for mongo db for first time. I am not able to convert the shell query which I wrote previously to java format. I am facing some issues. The below is the shell query which I wrote already and it's working fine.

Date set for rooms.

{
 "_id": ObjectId("571c5724db62826826d28d08"),
"conversationId": "6puebew70kke29",
"userId": "600",
"firstName": "Test",
"profileImagePath": "",
"created": ISODate("2016-04-24T05:18:28.753Z"),
"__v": 0
}
{
   "_id": ObjectId("571c5724db62826826d28d09"),
"conversationId": "6puebew70kke29",
"userId": "900",
"firstName": "User",
"profileImagePath": "",
"created": ISODate("2016-04-24T05:18:28.754Z"),
"__v": 0
 }

  {
"_id": ObjectId("571c574edb62826826d28d0b"),
"conversationId": "fsny11z742kpgb9",
"userId": "600",
"firstName": "FitTest",
"profileImagePath": "",
"created": ISODate("2016-04-24T05:19:10.192Z"),
"__v": 0
 }

  {
"_id": ObjectId("571c574edb62826826d28d0c"),
"conversationId": "fsny11z742kpgb9",
"userId": "800",
"firstName": "Dev",
"profileImagePath": "",
  "created": ISODate("2016-04-24T05:19:10.193Z"),
"__v": 0
    }



 rooms.aggregate([{
        $match: {
            type: 'PRIVATE'
        }
    }, {
        $group: {
            _id: '$conversationId',
            users: {
                $push: '$userId'
            }
        }
    }, {
        $match: {
            users: {
                $all: [friendProfileData.id, userprofileData.id]
            }
        }
    }, ]

Java code for the above query.

 Aggregation agg = newAggregation(
            match(Criteria.where("type").is("PRIVATE")),
            group("_id", "conversationId"),
            group("users").push("userId").as("users")
            );

    AggregationResults<Rooms> groupResults = mongoOps.aggregate(agg,   "rooms", Rooms.class);
    List<Rooms> result = groupResults.getMappedResults();

Not able to complete it fully still I am not aware how to write few expressions. Your help is appreciated.

4
  • 2
    Could you please update the question with sample "rooms" document? Commented Jun 29, 2016 at 12:54
  • @notionquest: I have updated please check it. Commented Jun 29, 2016 at 12:57
  • The sample documents provided doesn't have friendProfileData and userprofileData attributes. Initially, I assumed that Mongo query that you have provided is a working version for your requirement. But, now I am not 100% sure whether it is a working version. Commented Jun 29, 2016 at 14:56
  • @notionquest: The both the id will be dynamic , but the example you have given below with static id will be the scenario. Commented Jun 30, 2016 at 2:35

1 Answer 1

1

I have made an assumption as I am not sure about "friendProfileData" and "userprofileData" attributes in the last "match".

You can change the "Filters.all" statement accordingly as per your requirement. Otherwise, this code should meet your requirement and it works fine with "MongoDB 3.2.0" and "Mongo Java Driver 3.2.2 Jar".

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;

public static void main(String[] args) {
        MongoClient client = new MongoClient();
        MongoDatabase database = client.getDatabase("localhost");

        List<Bson> aggregateList = new ArrayList<>();

        aggregateList.add(Aggregates.match(Filters.eq("type", "PRIVATE")));
        aggregateList.add(Aggregates.group("$conversationId", Accumulators.push("users", "$userId")));
        aggregateList.add(Aggregates.match(Filters.all("users", Arrays.asList("1", "800"))));

        AggregateIterable<Document> mongoCollectionList = database.getCollection("rooms")
                .aggregate(aggregateList);

        MongoCursor<Document> mongoCursor = mongoCollectionList.iterator();

        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());

        }

    }

Maven Dependency:-

The above works fine with the below Maven dependency.

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.2.2</version>
</dependency>

Please note that the above may not work if you use the below jar:-

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.2.2</version>
</dependency>
Sign up to request clarification or add additional context in comments.

7 Comments

I used the above code but getting the below error.The method aggregate(List<? extends DBObject>) in the type DBCollection is not applicable for the arguments (List<Bson>)
Please check your Mongo Java Driver version. The above solution should work fine with the below jar. The solution has been tested successfully. <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.2</version> </dependency>
I am using exactly the same jar with the version what you have mentioned.
I have added the dependency including imports. Please note that there is some different between "mongodb-driver" and "mongo-java-driver" jar. They are not identical.
I am using the below gradle dependency //Mongo Java driver compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.2.2'
|

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.