Like $ and two documents in mongodb and java?

I am using mongodb with Java 3.0 driver. I have a scenario where I have to execute boolean and therefore $and in my queries. For example, I have two documents already created, and I'm trying to do something like this:

 iterable = mongoDatabase.getCollection("restaurants").find( new Document("$and", asList(abc, updatedDocumentTypeOne))); 

where abc is one document and updatedDocumentTypeOne is another document. I found this in the mongodb manual, but I get an error as I create the asList method first.

Or how to replicate the following in Java:

 db.inventory.find( { $and : [ { $or : [ { price : 0.99 }, { price : 1.99 } ] }, { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } ] } )` 
+4
source share
2 answers

You can also try the code below, which adds a filter for replicating requests in Java:

 // Where db is the object reference of "inventory" collection database MongoCollection<Document> inventory = db.getCollection("inventory"); //List for result return List<Document> result = new ArrayList<Document>(); //Query replication in Java and return result into the list inventory.find(Filters.and( Filters.or(Filters.eq("price", 0.99),Filters.eq("price", "1.99")), Filters.or(Filters.eq("sale", true),Filters.lt("qty", 20)) )).into(result); 
+4
source

Change from asList () to Arrays.asList ()

Instead of writing Arrays.asList (), you specified asList (). Therefore, the compiler is looking for the asList () method, which is NOT available.

Check out the code below:

 iterable = mongoDatabase.getCollection("restaurants").find( new Document("$and", Arrays.asList(abc, updatedDocumentTypeOne))); 

For your above request, you can program as shown below:

 /* First OR condition */ Document price1 = new BasicDBObject("price",0.99); Document price2 = new BasicDBObject("price",1.99); BasicDBList or_first = new BasicDBList(); or_first.add(price1); or_first.add(price2); DBObject query = new BasicDBObject("$or", or_first); /* Second OR condition */ boolean val = true; Document sale = new BasicDBObject("sale",val); Document qty = new BasicDBObject("qty", new BasicDocument("$lt",20)); BasicDBList or_second = new BasicDBList(); or_second.add(sale); or_second.add(qty); DBObject query = new BasicDBObject("$or", or_second); /* AND condition logic */ BasicDBList and_op = new BasicDBList(); and_op.add(or_first); and_op.add(or_second); iterable = mongoDatabase.getCollection("restaurants").find( new Document("$and", and_op )); 
+3
source

All Articles