0

I'm using MongoDB java driver 3.2.2 to do some aggregation operations, but I'm not sure if something could be achieved through it.

The original query in MongoDB is:

db.getCollection('report').aggregate({
$group: {
    _id: "$company_id",
    count: {
            $sum: {
                    $cond: [{
                            $eq: ["$idcard.status", "normal"]
                        },0,1]
                }
            }
    }
})

I have no idea of how to put the "$cond" as a parameter of "$sum" operator in Java driver in the code section below:

        AggregateIterable<Document> res = col.aggregate(Arrays.asList(
            group("$company_id",
                    sum("count", ...)
            )));

I've searched the official document about this with no result, anyone has experience of doing this? Thanks.

2 Answers 2

1

For 3.x drivers

Using BsonDocument : Type Safe Version

BsonArray cond = new BsonArray();
BsonArray eq = new BsonArray();
eq.add(new BsonString("$idcard.status"));
eq.add(new BsonString("normal"));
cond.add(new BsonDocument("$eq", eq));
cond.add(new BsonInt64(0));
cond.add(new BsonInt64(1));

AggregateIterable<BsonDocument> aggregate = dbCollection.aggregate(Arrays.asList(
        group("$company_id",
                sum("count", new BsonDocument("$cond", cond))
    )));

Using Document - Less Code but Not Type Safe

List cond = new ArrayList();
cond.add(new Document("$eq", Arrays.asList("$idcard.status", "normal")));
cond.add(0);
cond.add(1);

AggregateIterable<Document> aggregate = dbCollection.aggregate(Arrays.asList(
        group("$company_id",
                sum("count", new Document("$cond", cond))
        )));
Sign up to request clarification or add additional context in comments.

1 Comment

Finally I use the Document class for this case, thanks for the precise explanation of the difference!
0

To use $cond in Java use ArrayList.

{ $cond: [ { $eq: ["$idcard.status", "normal"] },0,1]

// To Acheive this - [ "$idcard.status", "normal" ]

ArrayList eqArrayList = new ArrayList();
eqArrayList.add("$idcard.status");
eqArrayList.add("normal");

// To Acheive this - [ { $eq: [ "$idcard.status", "normal" ] } , 1, 0 ]

 ArrayList condArray = new ArrayList();
 condArray.add(new BasicDBObject("$eq", eqArrayList));
 condArray.add(1);
 condArray.add(0);

// Finally - { $cond: [ { $eq: ["$idcard.status", "normal" ] } , 1, 0 ] }

BasicDBObject fullCond = new BasicDBObject("$cond", condArray);

Also see: MongoDB aggregation condition translated to JAVA driver

1 Comment

BasicDBObject is for 2.x driver version. BsonDocument and Document is recommended for 3.x driver version.

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.