Passing more than one $Unwind object from java driver

旧时模样 提交于 2019-12-12 01:28:16

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/18023160/passing-more-than-one-unwind-object-from-java-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!