mongodb AggregationOutput list.iterator() 无限循环的问题

本文探讨了在MongoDB中遍历聚合结果时出现无限循环的问题,并提供了正确的遍历方式,包括使用迭代器和foreach循环两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在mongodb中将获取到的聚集进行遍历的时候进入无限循环,代码:

	@Override
	public Object getLogwayList() {
		Iterable<DBObject> list= pageAnaDao.getLogwayList().results();
		while(list.iterator().hasNext()){
		    DBObject result = list.iterator().next();
		    String id = result.get("_id").toString();
		    Iterable<DBObject> listCount = (Iterable<DBObject>) result.get("counts");
			while(listCount.iterator().hasNext()){
			    DBObject resultOne = listCount.iterator().next();
			}
		}
	}

下边这句代码始终为真:

list.iterator().hasNext()
而下边这句一直返回到第一个元素:

DBObject result = list.iterator().next();
所以导致的结果就是不断遍历第一个元素,进入无限循环。正确的方式:

	@Override
	public Object getLogwayList() {
		Iterable<DBObject> list= pageAnaDao.getLogwayList().results();
		Iterator<DBObject> iterator= list.iterator();
		List<LogWay> results = new ArrayList<LogWay>();
		while(iterator.hasNext()){
		    DBObject result = iterator.next();
		    String id = result.get("_id").toString();
		    Iterable<DBObject> listCount = (Iterable<DBObject>) result.get("counts");
		    Iterator<DBObject> iteratorCount= listCount.iterator();
			while(iteratorCount.hasNext()){
			    DBObject resultOne = iteratorCount.next();
		}
		}

或者采用foreach()循环,进行:

	for (DBObject obj : output.results()) {
		String id = obj.get("_id");
		int times = Integer.parseInt(obj.get("times").toString());
		System.out.println("ID IS "+id+" time: "+times);
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值