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

时间:2014-06-22 17:03:30

标签: java mongodb find mongodb-query mongo-java

我尝试使用操作数和一起查询集合。我的shell版本正常运行:

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

任何想法有什么不对?

3 个答案:

答案 0 :(得分:5)

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

DBCursor cur = widgets.find(criteria);

答案 1 :(得分:2)

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

// 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 mongo聚合文档。

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

答案 2 :(得分:1)

考虑到这种情况,我建议采用以下解决方案作为替代方案,上述解决方案也应该可以正常工作。这是使用Criteria

    Query query = new Query();
    List<Criteria> criteriaList = new ArrayList<>();
Criteria criteriaCreatedBy1 = new Criteria().where("title").is("input");
criteriaList.add(criteriaCreatedBy1);
Criteria criteriaCreatedBy2 = new Criteria().where("name").is("name input");
criteriaList.add(criteriaCreatedBy2);
    query.addCriteria(new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));
    List<Screen> getSearchScreens = mongoTemplate.find(query,Screen.class,"collectionName");