在使用MongoDB Node.js驱动程序在MongoDB中执行某些操作时,结果以Cursor(游标)对象返回。Cursor对象作为一个可迭代的可在数据库中访问一组对象的游标。例如,当你使用find()时,实际的文档不在回调函数中返回;相反,返回的是cursor对象。然后,你可以使用该Curosr对象来读取结果的条目。
因为Cursor对象是可迭代的,所以在内部保持一个当前位置的索引。这样,你就可以一次读取多个条目。请记住,有些操作只影响Cursor对象的当前项目,并递增索引。其他操作则影响从目前索引往前的所有条目。
1,each(callback)
从当前游标索引开始遍历Cursor对象的条目并每次都调用回调函数。这可以让你在右边表示的每个条目上执行回调函数。回调函数接受err和item参数。
var MongoClient = require('mongodb').MongoClient; url = "mongodb://localhost:27017/test" MongoClient.connect(url,function(err,db){ dbo = db.db("test"); collectionIns = dbo.collection("products"); var i = 1; collectionIns.find({}).each(function(err,item){ console.log("这是第"+i+"个条目"); console.log(item); i +=1; }); });
运行结果:
这是第1个条目 { _id: 154, name: '笔记本电脑' } 这是第2个条目 { _id: 155, name: '耳机' } 这是第3个条目 { _id: 156, name: '台式电脑' } 这是第4个条目 { _id: 5b07ab43a9f106ce6ce1227c, id: '1111', name: 'xiaobaicai' } 这是第5个条目 { _id: 5b07abbaff6004f4cc35e72b, id: '1112', name: 'xiaobaicai' } 这是第6个条目 { _id: 5b07ac26462e1df41855a47f, id: '1112', name: 'xiaobaicai' } 这是第7个条目 { _id: 166, name: '白菜在练习' }
2,toArray(callback)
从当前右边索引开始向前遍历Cursor对象的条目并返回一个对象数组给回调函数。回调函数接收err和items.
var MongoClient = require('mongodb').MongoClient; url = "mongodb://localhost:27017/test" MongoClient.connect(url,function(err,db){ dbo = db.db("test"); collectionIns = dbo.collection("products"); var i = 1; collectionIns.find({}).toArray(function(err,item){ console.log("这是第"+i+"个条目"); console.log(item); i +=1; }); db.close(); });
运行结果:
这是第1个条目 [ { _id: 154, name: '笔记本电脑' }, { _id: 155, name: '耳机' }, { _id: 156, name: '台式电脑' }, { _id: 5b07ab43a9f106ce6ce1227c, id: '1111', name: 'xiaobaicai' }, { _id: 5b07abbaff6004f4cc35e72b, id: '1112', name: 'xiaobaicai' }, { _id: 5b07ac26462e1df41855a47f, id: '1112', name: 'xiaobaicai' }, { _id: 166, name: '白菜在练习' } ]
3,count(callback)
计算Cursor中对象的个数
var MongoClient = require('mongodb').MongoClient; url = "mongodb://localhost:27017/test" MongoClient.connect(url,function(err,db){ dbo = db.db("test"); collectionIns = dbo.collection("products"); var i = 1; collectionIns.find({}).count(function(err,item){ console.log("这是第"+i+"个条目"); console.log(item); i +=1; }); db.close(); });
运行结果:
7
4 close(callback)
释放cursor对象,从而释放客户端和MongoDB服务器上的内存
5,isClosed()
如果Cursor对象已关闭,返回true,否则返回false。