2
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());
            }
        }
1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for ur help.
1

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);

Comments

0

BasicDBList orList = new BasicDBList();

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.