How to create a query with ObjectIds using java?

I have a set of identifiers like:

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

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

  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 cannot find anything because it is the 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 an ObjectId("51eae100c2e6b6c222ec3431") in a list using java

+2
source share
1 answer

{ "$oid" : "51eae100c2e6b6c222ec3431"} matches the ObjectId("51eae100c2e6b6c222ec3431") in a different format only.

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

If the query does not find any documents (and you are sure that they are present in the collection), another problem arises. I would double check the server (s) you are connecting to, and the name of the database and collection.

Rob.

+3
source

Source: https://habr.com/ru/post/978213/


All Articles