如何查找符合多个条件的文档

我正在尝试使用操作数AND’d一起查询集合。 我有shell版本工作:

db.widgets.find({color: 'black, shape: 'round', weight: 100}) 

我无法找到Java等价物(使用本机驱动程序 )。 我尝试了各种各样的东西,但这是我最近的尝试:

 // Find all black, round widgets with weight 100 List criteria = new ArrayList(); criteria.add(new BasicDBObject("color", "black")); criteria.add(new BasicDBObject("shape", "round")); criteria.add(new BasicDBObject("weight", 100)); DBCursor cur = widgets.find(new BasicDBObject("$and", criteria)); // Get all matching widgets and put them into a list List widgetList = new ArrayList(); DBCursor cur = widgets.find(andQuery); while (cur.hasNext()) { widgetList.add(new Widget(cur.next())); } if (widgetList.isEmpty()) System.out.println("No results found"); 

有什么想法有什么不对?

 BasicDBObject criteria = new BasicDBObject(); criteria.append("color", "black"); criteria.append("shape", "round"); criteria.append("weight", 100); DBCursor cur = widgets.find(criteria); 

解决相同问题的另一种方法是使用聚合:

 // To print results Block printBlock = new Block() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; // get db connection and collection MongoDatabase db= mongoClient.getDatabase("dbname"); MongoCollection collection= database.getCollection("collectionname"); collection.aggregate(Arrays.asList(Aggregates.match(Filters.eq("key1", "value1")), Aggregates.match(Filters.eq("key2", "value2")), Aggregates.match(Filters.eq("key3", "value3")))).forEach(printBlock); 

有关更多详细信息,请参阅v 3.4 mongo聚合文档。

http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/aggregation/