3

I have set of ids like:

["51eae104c2e6b6c222ec3432", "51eae104c2e6b6c222ec3432", "51eae104c2e6b6c222ec3432"]

I need to find all documents using this set of ids.

    BasicDBObject query = new BasicDBObject(); 
    BasicDBList list = new BasicDBList();
    ObjectId ob1 = new ObjectId("51eae100c2e6b6c222ec3431");
    ObjectId ob2 = new ObjectId("51eae100c2e6b6c222ec3432");
    list.add(ob1);
    list.add(ob2);
    query.append("_id", new BasicDBObject("$in", list));

This query can't find anything because it is same as

{ "_id" : { "$in" : [ { "$oid" : "51eae100c2e6b6c222ec3431"} , { "$oid" : "51eae100c2e6b6c222ec3432"}]}}

To find something it must be

{_id:{$in:[ObjectId("51eae100c2e6b6c222ec3431") , ObjectId("51eae104c2e6b6c222ec3432")]}}

but I don't know how to make ObjectId("51eae100c2e6b6c222ec3431") in list using java

Guru_1010
  • 574
  • 7
  • 22
  • possible duplicate of [MongoDB Java: Finding objects in Mongo using QueryBuilder $in operator returns nothing](http://stackoverflow.com/questions/11650970/mongodb-java-finding-objects-in-mongo-using-querybuilder-in-operator-returns-n) – WiredPrairie Jul 21 '13 at 11:47

1 Answers1

3

{ "$oid" : "51eae100c2e6b6c222ec3431"} is the same as ObjectId("51eae100c2e6b6c222ec3431") just in a different format.

See this page for the different formats: http://docs.mongodb.org/manual/reference/mongodb-extended-json/

If the query is not finding any documents (and you are sure they are present in the collection) then there is some other issue. I would double check the server(s) you are connecting to and the name of the database and collection first.

Rob.

Rob Moore
  • 3,343
  • 17
  • 18
  • I just checked from mongo shell, this query {_id:{$in:[ { "$oid" : "51ebf50bc2e66fa145ddaa30"} , { "$oid" : "51ebf510c2e66fa145ddaa31"}]}} doesn't return anything though documents with these oids presented in the collection – Guru_1010 Jul 21 '13 at 14:54
  • 2
    The "shell mode" format is ObjectId("51eae100c2e6b6c222ec3431"). The Java Driver's JSON utility turns ObjectId's into the strict format { "$oid" : "51eae100c2e6b6c222ec3431"}. Does the query work from Java? – Rob Moore Jul 21 '13 at 15:23
  • Yes it works from java. Thank you. But another problem that query returns only one document instead of two. – Guru_1010 Jul 21 '13 at 15:56
  • Which one? The Java or Shell? If Java can you edit the question with what the code looks like to execute the query and consume the results? – Rob Moore Jul 21 '13 at 16:24
  • It does not show how you are executing the query. Just building the query document. – Rob Moore Jul 21 '13 at 19:57
  • I did `db.collection.find(query);` where collection is name of my collection – Guru_1010 Jul 22 '13 at 03:29