MongoDB Java: Finding objects in Mongo using QueryBuilder $in operator returns nothing

霸气de小男生 提交于 2019-12-01 06:53:46

You are now doing the equivalent of :

db.col.find({$in:[{Id:id1}, {Id:id2}, ..., {Id:idN}]})

Which is not a valid query since you're not specifying what field to $in on. I'm assuming you want :

db.col.find({Id:{$in:[id1, id2, ..., idN]}})

Change your query construction code accordingly and you should be fine.

EDIT: Adding correct code :

public static void getDocuments(List<Integer> documentIds) {

            BasicDBList docIds = new BasicDBList();
            docIds.addAll(documentIds)
            DBObject inClause = new BasicDBObject("$in", docIds);
            DBObject query = new BasicDBObject("Id", inClause);
            DBCursor dbCursor = mongoRule.getDatabase().getCollection("mycollection").find(query);
            System.out.println(dbCursor == null);
            if (dbCursor != null) {
                while (dbCursor.hasNext()) {
                    System.out.println("object -  " + dbCursor.next());
                }
            }
        } 

Please note that this assumes "Id" is something other than "_id"

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