mongo-查询(7)——使用游标

使用游标。

> db.tianyc05.find()
{ "_id" : 1, "age" : 32, "name" : { "first" : "tian", "last" : "yc" }, "sex" : "m" }
{ "_id" : 2, "age" : 27, "name" : { "first" : "tian", "last" : "yx" }, "sex" : "m" }
{ "_id" : 3, "age" : 35, "name" : { "first" : "tian", "last" : "jl" }, "sex" : "f" }
> var a=db.tianyc05.find()
> a.hasNext()
true
> a.next()
{
"_id" : 1,
"age" : 32,
"name" : {
"first" : "tian",
"last" : "yc"
},
"sex" : "m"
}
> a.hasNext()
true
> a.next()
{
"_id" : 2,
"age" : 27,
"name" : {
"first" : "tian",
"last" : "yx"
},
"sex" : "m"
}
> a.hasNext()
true
> a.next()
{
"_id" : 3,
"age" : 35,
"name" : {
"first" : "tian",
"last" : "jl"
},
"sex" : "f"
}
> a.hasNext()
false
> a.next()
Mon Feb 04 14:52:12 uncaught exception: error hasNext: false
>

 

> db.tianyc05.find()
{ "_id" : 1, "age" : 32, "name" : { "first" : "tian", "last" : "yc" }, "sex" : "m" }
{ "_id" : 2, "age" : 27, "name" : { "first" : "tian", "last" : "yx" }, "sex" : "m" }
{ "_id" : 3, "age" : 35, "name" : { "first" : "tian", "last" : "jl" }, "sex" : "f" }
> db.tianyc05.find().limit(2)
{ "_id" : 1, "age" : 32, "name" : { "first" : "tian", "last" : "yc" }, "sex" : "m" }
{ "_id" : 2, "age" : 27, "name" : { "first" : "tian", "last" : "yx" }, "sex" : "m" }
> db.tianyc05.find().limit(2).skip(1)
{ "_id" : 2, "age" : 27, "name" : { "first" : "tian", "last" : "yx" }, "sex" : "m" }
{ "_id" : 3, "age" : 35, "name" : { "first" : "tian", "last" : "jl" }, "sex" : "f" }
> db.tianyc05.find().limit(2).skip(1).sort(age:1)
Mon Feb 04 14:57:11 SyntaxError: missing ) after argument list (shell):1
> db.tianyc05.find().limit(2).skip(1).sort({age:1})
{ "_id" : 1, "age" : 32, "name" : { "first" : "tian", "last" : "yc" }, "sex" : "m" }
{ "_id" : 3, "age" : 35, "name" : { "first" : "tian", "last" : "jl" }, "sex" : "f" }
> db.tianyc05.find().limit(2).skip(1).sort({age:-1})
{ "_id" : 1, "age" : 32, "name" : { "first" : "tian", "last" : "yc" }, "sex" : "m" }
{ "_id" : 2, "age" : 27, "name" : { "first" : "tian", "last" : "yx" }, "sex" : "m" }
>

使用skip略过少量文档还是不错的,但要是略过太多的话,skip就会变得很慢。所以虽然用skip来做分页查询很方便,但还是不建议这样用。

posted @ 2013-02-04 15:09  醇酒醉影  阅读(1746)  评论(0编辑  收藏  举报