[cbmongodb]: Unable to query _id with $in

Hi Jon,

I was having an issue with dynamically querying documents based on _id using $in operator. No results (empty array) are returned.
I believed this issue is specific to _id. When I tested using a different fields other than _id, it worked fine. Any thoughts?

/* Returns empty array */
structInsert(this.get_criteria(), “_id”, {"$in"=[“56ff5d0b659b424c7801234”]});

/* Returns correct results */
structInsert(this.get_criteria(), “state”, {"$in"=[“MI”,“WI”]});
structInsert(this.get_criteria(), “_id”, “56ff5d0b659b424c7801234”);

For _id queries, if a string value is detected, the module will auto-cast it to the Mongo BSON ObjectId before the query is run against the database.

Because this is a struct, you’ll need to manually cast those _id values to Mongo BSON objects like so:


var searchIds = ["56ff5d0b659b424c7801234"];

for( var i=1; i<=arrayLen(searchIds); i++; ){

    searchIds[i] = this.getMongoUtil().newObjectIdFromId( searchIds[i] );

}

//Note that you can use the where function
this.appendCriteria( {'_id':{"$in": searchIds}} );

var searchResults = this.findAll();

I’ll add a ticket to perform auto-casting on $in queries for _id’s and add IN as a second argument to the where function. It will be backward compatibile since, if you pass a BSON id to newObjectIdFromId it will return the original if it’s already cast as the Mongo object.

Also, from CBMongoDB version 3.2.0.4 and up, you can pass in a criteria struct directly to the where function like so:

this.where( {'_id':{"$in": searchIds}} );

Thanks so much for the answer!
newObjectIdFromId() solved the issue.