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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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
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?
Yes it works from java. Thank you. But another problem that query returns only one document instead of two.
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?
It does not show how you are executing the query. Just building the query document.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.