由DBCursor的“can't switch cursor access methods”异常引发的思考

本文详细解析了在使用MongoDB的DBCursor时遇到的can't switch cursor access methods错误,阐述了错误产生的原因在于cursor类型的切换,并提供了正确的遍历方法,即使用foreach进行遍历。

先谈谈我是怎么用的:

 DBCollection dbcollection =  XXXXXXXXXX();  //连接mongo
        DBCursor dbCursor = mergeVideoDB.find(XXXX);  //根据name查出若干个 
        if (dbCursor.length() == 1) {
            return videoinfos;
        }
        while(dbcursor。hasNext()){    // 这一步产生错误,报出DBCursor的“can't switch cursor access methods”
           XXXXXX;
     }
以上!

首先在使用hasNext方法后需要先通过 _checkType() 检查 cursor 类型。 

 1 void _checkType( CursorType type ){
 2         if ( _cursorType == null ){
 3             _cursorType = type;
 4             return;
 5         }
 6 
 7         if ( type == _cursorType )
 8             return;
 9 
10         throw new IllegalArgumentException( "can't switch cursor access methods" );
11     }

回过头来看,  DBCursor dbCursor = mergeVideoDB.find(XXXX); //根据name查出若干个  

此时,DBCursor的type为 null

 if (dbCursor.length() == 1) {
            return videoinfos;
        }

在执行完上述步骤后,DBCursor的type变为了array

所以在使用hasNext方法时会报出

"can't switch cursor access methods"
解决思路:
1.不要在之前使用会更改其type的方法进行操作;
2.使用除hasNext之外的其他遍历方法进行遍历
直接使用foreach方法进行遍历即可:
for (DBObject dbObject:dbCursor){}。
 



转载于:https://www.cnblogs.com/hanhaotian/p/9729606.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值