How to find documents matching multiple criteria
Asked Answered
F

4

8

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', weight: 100})

I'm unable to find the Java equivalent (using the native driver). I've tried various things, but here is my latest attempt:

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

Any ideas what is wrong?

Folkway answered 22/6, 2014 at 17:3 Comment(0)
S
7
BasicDBObject criteria = new BasicDBObject();
criteria.append("color", "black");
criteria.append("shape", "round");
criteria.append("weight", 100);

DBCursor cur = widgets.find(criteria);
Scrivner answered 22/6, 2014 at 19:53 Comment(0)
W
1

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/

Walk answered 27/10, 2017 at 19:23 Comment(0)
E
0

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");
Elisavetpol answered 14/4, 2020 at 23:50 Comment(2)
I'd keen to hear what approach would be better. One of the challenges that I see with this approach that it didn't provide any pagination functionality.Elisavetpol
This is a only a "Springframework" solutom. Not pure Java & MongoDB.Heliostat
G
0

This can call addCriteria method as much as you can.

Query query = new Query()

query.addCriteria(Criteria.where("firstname").is("Bruce"));
query.addCriteria(Criteria.where("lastname").is("Wayne"));

List<User> users = mongoTemplate.find(query, User.class);
Garling answered 17/6, 2023 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.