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

前端 未结 1 408
傲寒
傲寒 2021-01-13 21:24

I have a JUnit rule called as MongoRule looks like

public class MongoRule extends ExternalResource {

    private static final Lo         


        
相关标签:
1条回答
  • 2021-01-13 22:05

    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"

    0 讨论(0)
提交回复
热议问题