如何一个接一个地从Mongo-DB检索记录

时间:2019-03-04 16:46:17

标签: mongodb spring-data-mongodb

我需要帮助,在Mongo-DB Collection中有30,000条记录。我想一次检索一个文档,然后再次检索同一文档。 我正在使用Spring Boot

类似查询:-

    public class SearchServer
    {

        private static java.util.concurrent.locks.Lock delayLock = new ReentrantLock();
        private static AtomicInteger queryQueue = new AtomicInteger();
        private static AtomicLong queryDelay = new AtomicLong();

        static void doDelayQuery()
        {
            delayLock.lock();
            try
            {
                if(isUserCancelled())
                {
                    return;
                }
                //Ensure only send one query a second
                Date currentDate = new Date();
                long delay = currentDate.getTime() - querySentDate.getTime();
                if (delay < delayInMilliseconds)
                {
                    try
                    {
                        long delayBy = delayInMilliseconds - delay;
                        queryDelay.addAndGet(delayBy);
                        Thread.sleep(delayBy);
                        logger.info(Thread.currentThread().getName() + ":Delaying for " + delayBy + " ms");
                    }
                    catch (InterruptedException ie)
                    {
                        Thread.currentThread().interrupt();
                        throw new UserCancelException("User Cancelled whilst thread was delay sleeping");
                    }
                }
            }
            finally
            {
                //We set before unlocking so that if another thread enters this method before we start query we ensure they
                //do not skip delay just because the query that this thread has delayed for has started
                querySentDate = new Date();
                delayLock.unlock();
            }

        }
    }

以及下次在where部分设置新的ID进行比较

1 个答案:

答案 0 :(得分:0)

我通过对上面的查询使用该方法逻辑找到了解决方案。希望对你有帮助

private @Autowired StockPriceRepository stockPriceRepo;
private @Autowired MongoTemplate mongoTemplate;
private static String _id = "";
private static volatile Boolean isFirstRead = false;

public StockPrice fetchUuIdAndDate(Integer limit) {
    logger.info("Fetch UuId And Date :- (limit : "+ limit + ")");
    Query query = new Query();
    query.fields().include("date");
    query.with(new Sort(Sort.Direction.ASC, "_id"));
    query.limit(limit == 1 ? limit: 1);
    StockPrice stockPrice;
    if(!isFirstRead) { // only 1 time
        stockPrice = this.mongoTemplate.findOne(query, StockPrice.class);
        _id = stockPrice.getUuId();
        isFirstRead = true;
    } else {
        query.addCriteria(Criteria.where("_id").gt(_id));
        stockPrice = this.mongoTemplate.findOne(query, StockPrice.class);
        _id = stockPrice.getUuId();
    }
    logger.info("Query :- " + query.toString());
    return stockPrice;
}