Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } } ] }
    ]
} )`
like image 562
Shaik Mujahid Ali Avatar asked Aug 13 '15 08:08

Shaik Mujahid Ali


People also ask

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

How do I merge two conditions in MongoDB?

In MongoDB, we can apply the multiple conditions using the and operator. By applying the and operation we will select all the documents that satisfy all the condition expressions. We can use this operator in methods like find(), update() , etc as per the requirement.

Can I use Java with MongoDB?

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT. You need to download the jar mongodb-driver-3.11.


1 Answers

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);
like image 193
HaRLoFei Avatar answered Sep 30 '22 08:09

HaRLoFei