HMdeveloper
HMdeveloper

Reputation: 2884

where clause for array on mongo does not work

I am new to mongodb, I have a document in my db as follow:

{ "_id" : { "$oid" : "546e916cd38e0b3e0e79592f"} , "name" : "hamed" , "entity" : [ "1" , "2"]}

Now I want to read aal docs that entity=["1","2"] for that I tried the following code :

MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("test");
    Set<String> colls = db.getCollectionNames();
    DBCollection coll = db.getCollection("test");
    DBObject oredrFields = new BasicDBObject();
    oredrFields.put("entity", ":{ $in: ['1', '2'] } }");
    DBCursor cursor = coll.find(oredrFields);
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

But it does not return anything... Can anyone help how I can write my where clause correctly?

Upvotes: 0

Views: 320

Answers (2)

BatScream
BatScream

Reputation: 19700

You need to pass your query parameters as DBObject. You are missing an DBObject for the $in operator.

If you want only those records that have both "1" and "2", you need to use $all instead of $in, which returns only those documents whose entity field contain all the elements in the passed array.

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("test");
    DBCollection coll = db.getCollection("test");
    DBObject oredrFields = new BasicDBObject();
    DBObject inQuery = new BasicDBObject().append("$all", new String[]{"1","2"});
    oredrFields.put("entity", inQuery);
    DBCursor cursor = coll.find(oredrFields);
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

Upvotes: 1

anhlc
anhlc

Reputation: 14469

$in should be a BasicDBObject as well:

DBObject oredrFields = new BasicDBObject();
DBObject inOp = new BasicDBObject();
inOp .put("$in", new String[]{"1","2"});
oredrFields.put("entity", inOp);

Upvotes: 1

Related Questions