日期:2014-05-16  浏览次数:20337 次

mongodb中分页显示数据集的学习
  这次继续看mongodb中的分页。首先依然是插入数据:

1)
db.Blog.insert( { name : "Denis",  age : 20, city : "Princeton" } )
db.Blog.insert( { name : "Abe",    age : 30, city : "Amsterdam" } )
db.Blog.insert( { name : "John",   age : 40, city : "New York"  } )
db.Blog.insert( { name : "Xavier", age : 10, city : "Barcelona" } )
db.Blog.insert( { name : "Zen",    age : 50, city : "Kyoto"     } )


2) 查询下
   db.Blog.find()
  结果为:
{ "_id" : ObjectId("51028ae0a8c33b71ed76a807"), "name" : "Denis", "age" : 20, "city" : "Princeton" }
{ "_id" : ObjectId("51028ae0a8c33b71ed76a808"), "name" : "Abe", "age" : 30, "city" : "Amsterdam" }
{ "_id" : ObjectId("51028ae2a8c33b71ed76a809"), "name" : "John", "age" : 40, "city" : "New York" }
{ "_id" : ObjectId("51028ae2a8c33b71ed76a80a"), "name" : "Xavier", "age" : 10, "city" : "Barcelona" }
{ "_id" : ObjectId("51028ae4a8c33b71ed76a80b"), "name" : "Zen", "age" : 50, "city" : "Kyoto" }


3)每次只显示2条,使用limit就可以了
   db.Blog.find().limit(2)

结果:
   { "_id" : ObjectId("5103e22c88a39c3c0b2585e1"), "name" : "Denis", "age" : 20, "city" : "Princeton" }
{ "_id" : ObjectId("5103e22d88a39c3c0b2585e2"), "name" : "Abe", "age" : 30, "city" : "Amsterdam" }
  需要排下序,没问题,加上sort就可以了
   ,比如根据name排序
  db.Blog.find().sort({name: 1}).limit(2)
 
{ "_id" : ObjectId("5103e22d88a39c3c0b2585e2"), "name" : "Abe", "age" : 30, "city" : "Amsterdam" }
{ "_id" : ObjectId("5103e22c88a39c3c0b2585e1"), "name" : "Denis", "age" : 20, "city" : "Princeton" }
   如果只需要显示某些列,可以这样:
   db.Blog.find(null, {name: 1, _id: 0}).sort({name: 1}).limit(2)
   _id:0这样的方式,连id列也不显示了

  只显示
  { "name" : "Abe" }
{ "name" : "Denis" }
   
3 分页
   比如要范围第3,第4条记录,使用skip(2),跳过2条

db.Blog.find(null, {name: 1, _id: 0}).sort({name: 1}).limit(2).skip(2)
   结果为:
{ "name" : "John" }
{ "name" : "Xavier" }

如果skip的数超过记录条数,也是不会报错的了:

  比如:
db.Blog.find(null, {name: 1, _id: 0}).sort({name: 1}).limit(2).skip(6)

   另外,使用$natural参数可以倒过来输出所有记录,比如:
  db.Blog.find().sort( { $natural: -1 } )
{ "_id" : ObjectId("5103eaa688a39c3c0b2585ed"), "name" : "Zen", "age" : 50, "city" : "Kyoto" }
{ "_id" : ObjectId("5103eaa588a39c3c0b2585ec"), "name" : "Xavier", "age" : 10, "city" : "Barcelona" }
{ "_id" : ObjectId("5103eaa588a39c3c0b2585eb"), "name" : "John", "age" : 40, "city" : "New York" }
{ "_id" : ObjectId("5103eaa588a39c3c0b2585ea"), "name" : "Abe", "age" : 30, "city" : "Amsterdam" }
{ "_id" : ObjectId("5103eaa588a39c3c0b2585e9"), "name" : "Denis", "age" : 20, "city" : "Princeton" }
   要注意的是,居然说超过32MB  会报错,说要用 cursor.limit()或者在要排序的列中创建索引,才不报错?