MongoDB 文档游标

查询结果遍历

当我们把查询结果赋值给一个JS变量的时候,查询结果其实是一个游标

  • 可以通过下标来访问查询结果 item
  • 可以迭代、遍历

打印出所有item1

> var cursor=db.accounts.find({name:'alice2'});
> while(cursor.hasNext()){ print(cursor.next()) }
[object BSON]
[object BSON]
[object BSON]
[object BSON]

打印出所有item2

> var cursor=db.accounts.find({name:'alice2'});
> cursor.forEach(function(item){ print(item) })

skip 和 limit

> db.accounts.find({name:'alice2'}).limit(3).skip(1)
{ "_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"), "name" : "alice2", "balance" : 100 }
{ "_id" : ObjectId("5d7f8f0da7b5867462dee50f"), "name" : "alice2", "balance" : 100, "contact" : [ 13611111111, "Guangzhou" ] }
{ "_id" : ObjectId("5d7f8f21a7b5867462dee510"), "name" : "alice2", "balance" : 100, "contact" : [ [ 13611111111, 13622222222 ], "Guangzhou" ] }

count

查询记录数量

# 默认情况下,count 函数不会考虑 skip 和 limit 的影响
> db.accounts.find({name:'alice2'}).limit(3).count()
18
# count 函数传 true 参数之后,就会考虑 skip 和 limit 的影响了
> db.accounts.find({name:'alice2'}).limit(3).count(true)
3
# 在不提供筛选条件的时候,count 函数并不会遍历文档,而是通过meta来返回文档数量。在分布式数据库结构较为复杂的时候,此时通过meta来获取,会不太准确,应该通过聚合管道来获取
> db.accounts.find().count()
31

sort

1 为升序,-1 为降序

> db.accounts.find().sort({balance:-1})
{ "_id" : ObjectId("5d7f25f4aecbd2bc0fa821b3"), "name" : "charlie", "balance" : 500 }
{ "_id" : ObjectId("5d7f26b6aecbd2bc0fa821b6"), "name" : "david", "balance" : 200 }
原文地址:https://www.cnblogs.com/zy108830/p/12639618.html