Find documents matching multiple criteria

I am trying to query a collection using AND'd operands together. I have a shell version:

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

I cannot find the Java equivalent (using the native driver ). I tried different things, but here is my last 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?

+4
source share
2 answers
BasicDBObject criteria = BasicDBObject();
criteria.append("color", "black");
criteria.append("shape", "round");
criteria.append("weight", 100);

DBCursor cur = widgets.find(criteria);
+4
source

Another way to solve this problem is to use 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 information, see the aggregation documentation v 3.4 mongo.

http://mongodb.imtqy.com/mongo-java-driver/3.4/driver/tutorials/aggregation/

+1

Source: https://habr.com/ru/post/1545574/


All Articles