The mongo java driver takes var args for aggregate method, I have an API in which $unwind
objects get's created dynamically and its number is not fixed. how can I pass it through Mongo Java driver aggregate method, as it needs each object to be passed separately. I tried passing putting all the $unwind
object in a BasicDBList and pass, but it fails. Can someone help me with some work around?
example:
db.foo.aggregate({$unwind:items},{$unwind:item2})
, but these unwind may vary as it is getting created at runtime.
you don't need to create a BasicDBList. This is how it works:
List<DBObject> unwindItems = new ArrayList<>();
if(<item2 is not null>){ //pseudo code
DBObject unwindItem1 = new BasicDBObject("$unwind", "$item1");
unwindItems.add(unwindItem1);
}
if(<item2 is not null>){ //pseudo code
DBObject unwindItem2 = new BasicDBObject("$unwind", "$item2");
unwindItems.add(unwindItem2);
}
//add any other dbObject in the list, it need not be an unwind operation, it could be match, project, group etc.
DBObject command = new BasicDBObject("aggregate", "foo");
command.put("pipeline", dbObjects);