Java code for mongodb aggregation query with $in

2.2k views Asked by At

I am new to mongodb and need an equivalent code in java for the below

db.asset.aggregate([{
            $unwind : '$asset'
        }, {
            $match : {
                'asset.status' : {
                    $in : ['1', '2', '3']
                },
                'asset.siteid' : {
                    $in : ['123']
                }
            }
        }
    ]).pretty()

I tried the following but it didn't help-out

    DBObject unwind = new BasicDBObject("$unwind", "$dp.asset");
    DBObject match  = BasicDBObjectBuilder.start().push("$match")
                  .push("dp.asset.status").add("$in", ['ACTIVE', 'LIMITEDUSE', 'OPERATING'])
                  .push("dp.asset.siteid").add("$in", ['BEDFORD']).get();

    AggregationOutput aggr = collection.aggregate(Arrays.asList(unwind, match));

Note : i am using mongodb 3.4.1

2

There are 2 answers

0
s7vr On BEST ANSWER

Not sure why you are using single quotes while passing the array value.

The right syntax to pass the values are

 DBObject match  = BasicDBObjectBuilder.start().push("$match")
             .push("$dp.asset.status").add("$in", Arrays.asList("ACTIVE", "LIMITEDUSE", "OPERATING"))
             .push("$dp.asset.siteid").add("$in", Arrays.asList("BEDFORD")).get();

Or

DBObject match  = BasicDBObjectBuilder.start().push("$match")
             .push("$dp.asset.status").add("$in", new String[]{"ACTIVE", "LIMITEDUSE", "OPERATING"})
             .push("$dp.asset.siteid").add("$in", new String[]{"BEDFORD"}).get();

For 3.x drivers, you should be using Document.

Document unwind = new Document("$unwind", "$dp.asset");
Document match  = new Document("$match", new Document("$dp.asset.status", new Document("$in", new String[]{"ACTIVE", "LIMITEDUSE", "OPERATING"})).
             append("$dp.asset.siteid", new Document("$in", new String[]{"BEDFORD"})));

Code for Mongo Query.

 Document unwind = new Document("$unwind", "$asset");
 Document match  = new Document("$match", new Document("$asset.status", new Document("$in", new String[]{"1", "2", "3"})).
         append("$asset.siteid", new Document("$in", new String[]{"123"})));
1
chridam On

The fields in your mongo shell aggregation operation do not match with the ones in the current Java pipeline.

Apart from that anomaly, you could try the following pipeline:

BasicDBList statusList = new BasicDBList();
statusList.add("1");
statusList.add("2");
statusList.add("3");
DBObject statusInClause = new BasicDBObject("$in", statusList);  

BasicDBList idList = new BasicDBList();
idList.add("123");
DBObject siteIdInClause = new BasicDBObject("$in", idList); 

DBObject fields = new BasicDBObject("asset.status", statusInClause);
fields.put("asset.siteid", siteIdInClause);

DBObject unwind = new BasicDBObject("$unwind", "$asset");
DBObject match = new BasicDBObject("$match", fields); 

AggregationOutput aggr = collection.aggregate(Arrays.asList(unwind, match));