How to find documents matching multiple criteria

后端 未结 3 650
滥情空心
滥情空心 2020-12-16 05:19

I\'m trying to query a collection using operands AND\'d together. I\'ve got the shell version working:

db.widgets.find({color: \'black, shape: \'round\', wei         


        
相关标签:
3条回答
  • 2020-12-16 05:52
    BasicDBObject criteria = new BasicDBObject();
    criteria.append("color", "black");
    criteria.append("shape", "round");
    criteria.append("weight", 100);
    
    DBCursor cur = widgets.find(criteria);
    
    0 讨论(0)
  • 2020-12-16 05:52

    I think the solution above should also work just fine, given the situation I'd suggest the following as an alternative. This is using 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");
    
    0 讨论(0)
  • 2020-12-16 06:00

    Another way to solve same problem is using aggregation:

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

    For more details please refer the v 3.4 mongo Aggregation documentation.

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

    0 讨论(0)
提交回复
热议问题