Iterate over large collection in MongoDB via spring-data

前端 未结 7 2048
误落风尘
误落风尘 2021-01-31 17:18

Friends!

I am using MongoDB in java project via spring-data. I use Repository interfaces to access data in collections. For some processing I need to iterate over all el

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 17:57

    You may want to try the DBCursor way like this:

        DBObject query = new BasicDBObject(); //setup the query criteria
        query.put("method", method);
        query.put("ctime", (new BasicDBObject("$gte", bTime)).append("$lt", eTime));
    
        logger.debug("query: {}", query);
    
        DBObject fields = new BasicDBObject(); //only get the needed fields.
        fields.put("_id", 0);
        fields.put("uId", 1);
        fields.put("ctime", 1);
    
        DBCursor dbCursor = mongoTemplate.getCollection("collectionName").find(query, fields);
    
        while (dbCursor.hasNext()){
            DBObject object = dbCursor.next();
            logger.debug("object: {}", object);
            //do something.
        }
    

提交回复
热议问题