psmaster psmaster - 3 months ago 68
Java Question

Mongo Query with $in array in Java

I am trying to create this query from

Java
for
MongoDB
.
Do you know how can I construct it in java?

db.node.find({
connectedWithIds: { $in: [
ObjectId('56bca32fe74a987ad8724da1')
] }
})


I tried to use this:

ObjectId arr[] = {new ObjectId("5409ae2e2cdc31c5aa0ce0a5")};
BasicDBObject inQuery = new BasicDBObject("$in", arr);
BasicDBObject query = new BasicDBObject("connectedWithIds", inQuery);


but the results is below:

{ "connectedWithIds" : { "$in" : [ { "$oid" : "5409ae2e2cdc31c5aa0ce0a5"}]}}


and occurs this error:

error: {
"$err" : "Can't canonicalize query: BadValue cannot nest $ under $in",
"code" : 17287
}

Answer

I could overcome this error with the code below:

    ArrayList<ObjectId> vals = new ArrayList<ObjectId>();
    vals.add(objectId);       
    BasicDBObject inQuery = new BasicDBObject("$in", vals);
    BasicDBObject query = new BasicDBObject("connectedWithIds", inQuery);
    List<BasicDBObject> users = (List<BasicDBObject>) customQueryManager.executeQuery("node", query);