dev777
dev777

Reputation: 1019

How to use "$or" operator using documents in mongodb using java

Document query = new Document();
            query.put("firstName", "abc");
            query.put("firstName", "xyz");

Here,"abc" is overrided by the "xyz".So,in the query I'm getting only one value i.e,xyz.I don't know,why the query getting overrided.can u please help me out...

My code:

MongoClient mongo = new MongoClient("localhost",27017);
        MongoDatabase db = mongo.getDatabase("sample");
        MongoCollection<Document> coll = db.getCollection("users");


        Document query = new Document();
        query.put("firstName", "abc");
        query.put("firstName", "xyz");

        Document docStatus =new Document("$or",query );
        try (MongoCursor<Document> cursor = coll.find(query).iterator()) {
            while (cursor.hasNext()) {
            System.out.println(cursor.next());
            }
        }

Upvotes: 2

Views: 3037

Answers (3)

Tamil Arasi
Tamil Arasi

Reputation: 179

BasicDBList orList = new BasicDBList();

orList.add(new BasicDBObject("FirstName","xxx"));

orList.add(new BasicDBObject("LastName","yyy"));

BasicDBObject dbObj = new BasicDBObject("$or",orList);

Upvotes: 0

Blakes Seven
Blakes Seven

Reputation: 50406

The arguments to the $or operator are a List, therefore you are just contructing a List of Document:

Document query = new Document(
  "$or", Arrays.asList(
    new Document("firstname", "abc"),
    new Document("firstname", "xyz")
  )
)

But really, when you want an $or condition on the same property, use $in instead. Which is of course another List but just of values:

Document query = new Document(
    "firstname",
    new Document(
        "$in", Arrays.asList("abc","xyz")
    )
)

Which is much shorter syntax for the selection of "either" value on the same document property.

Upvotes: 2

Rahul
Rahul

Reputation: 16335

You need to construct your query as below :

DBObject clause1 = new BasicDBObject("firstName", "abc");  
DBObject clause2 = new BasicDBObject("firstName", "xyz");    
BasicDBList or = new BasicDBList();
or.add(clause1);
or.add(clause2);
DBObject query = new BasicDBObject("$or", or);

Upvotes: 1

Related Questions