简体   繁体   中英

Not able to execute the mongo db aggregate query using java,

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.

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>

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