MongoDB: $in with an ObjectId array -


just quick question i've experienced , i'm still thinking why:

mongos> db.tickets.count({ "idreferencelist" : { "$in" : [ { "$oid" : "53f1f09f2cdcc8f339e5efa2"} , { "$oid" : "5409ae2e2cdc31c5aa0ce0a5"}]}}); 

0

mongos> db.tickets.count({ "idreferencelist" : { "$in" : [ objectid("53f1f09f2cdcc8f339e5efa2") , objectid("5409ae2e2cdc31c5aa0ce0a5")]}}); 

2

i thought both $oid , objectid spelling formats same mongodb. know why first query return 0 results , second 1 returning 2 (the right answer)?

furthermore, i'm using morphia framework uses mongodb java driver interact mongodb. i've realised there exists problem searching $in operator in objectids arrays on fields not _id executing lines of code:

list< objectid > fparams = new arraylist< objectid >();  fparams.add(...);  query<ticket> query = genericdao.createquery();  query.field("idreferencelist").in(fparams);  result = genericdao.find(query).aslist(); 

thank in advance.

regards,

  • luis cappa

both these formats valid representations of object id in mongodb, according documentation,

http://docs.mongodb.org/manual/reference/mongodb-extended-json/

and represented differently in 2 modes,

    strict mode         mongo shell mode     -----------         ----------------     { "$oid": "<id>" }  objectid( "<id>" ) 

so, query fields contain objectid, shell/console mode, need use objectid("<id>"). syntax followed in mongo shell mode.

hence query:

db.tickets.count({ "idreferencelist" : { "$in" : [ objectid("53f1f09f2cdcc8f339e5efa2") , objectid("5409ae2e2cdc31c5aa0ce0a5")]}}); 

would return row count.

now via java api,

you need below:

string[] ids = {"53f1f09f2cdcc8f339e5efa2","5409ae2e2cdc31c5aa0ce0a5"}; objectid[] objarray = new objectid[ids.length];  for(int i=0;i<ids.length;i++) {     objarray[i] = new objectid(ids[i]); }  basicdbobject inquery = new basicdbobject("$in", objarray); basicdbobject query = new basicdbobject("idreferencelist", inquery); dbcursor cursor = db.collection.find(query); while(cursor.hasnext()) {     dbobject doc = cursor.next();     // process doc. } 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -