Shaik Mujahid Ali
Shaik Mujahid Ali

Reputation: 2378

How to $and two documents in mongodb and Java?

I am using mongodb with Java 3.0 driver. I have a scenario where I have to perform logical and i.e, $and on my queries. For example, I have two documents already created and I am 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 mongodb manual but I am getting error as first create asList Method.

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 } } ] }
    ]
} )`

Upvotes: 6

Views: 4115

Answers (2)

HaRLoFei
HaRLoFei

Reputation: 316

You can also try the code below that adds a filter for query replication in Java:

// Where db is the object reference of "inventory" collection's 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);

Upvotes: 6

Yathish Manjunath
Yathish Manjunath

Reputation: 2029

Change from asList() to Arrays.asList()

Instead of writing Arrays.asList(), you have specified as asList(). So compiler is searching for the method asList(), which is NOT available.

Check the below code :

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

For your above query, You can code as 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 )); 

Upvotes: 2

Related Questions