2014-06-22 53 views
4

我在查詢使用操作數AND'd在一起的集合。我已經得到了外殼版本工作:如何查找符合多個條件的文檔

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

我無法找到相當於Java(使用native driver)。我嘗試了各種各樣的東西,但這裏是我的最新嘗試:

// Find all black, round widgets with weight 100 
List<BasicDBObject> criteria = new ArrayList<BasicDBObject>(); 
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<Widget> widgetList = new ArrayList<Widget>(); 
DBCursor cur = widgets.find(andQuery); 
while (cur.hasNext()) { 
    widgetList.add(new Widget(cur.next())); 
} 

if (widgetList.isEmpty()) 
    System.out.println("No results found"); 

任何想法是什麼錯?

回答

4
BasicDBObject criteria = BasicDBObject(); 
criteria.append("color", "black"); 
criteria.append("shape", "round"); 
criteria.append("weight", 100); 

DBCursor cur = widgets.find(criteria); 
+0

謝謝...完美的作品! –

1

另一種方式來解決同一個問題是使用聚合:

// To print results 
    Block<Document> printBlock = new Block<Document>() { 
     @Override 
     public void apply(final Document document) { 
      System.out.println(document.toJson()); 
     } 
    };  

// get db connection and collection 
MongoDatabase db= mongoClient.getDatabase("dbname"); 
    MongoCollection<Document> 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蒙戈聚集文檔。

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