How to create query with ObjectIds using java?

五迷三道 提交于 2020-01-15 07:42:20

问题


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:


{ "$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.



来源:https://stackoverflow.com/questions/17771297/how-to-create-query-with-objectids-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!