MongoDB使用游标来处理find查询到的结果文档集;
游标的使用实例:
1
2
3
4
5
6
7
8
9
|
> var cursor=db.post.
find
({
"name.firstname"
:
"joe"
})
> cursor
{
"_id"
: ObjectId(
"54ace1394ba07ed75df68f90"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 28 }
{
"_id"
: ObjectId(
"54ace753eab1d0ba4abb48ab"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace777eab1d0ba4abb48ac"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 10 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace781eab1d0ba4abb48ad"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 6 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace785eab1d0ba4abb48ae"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 5 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace789eab1d0ba4abb48af"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 7 },
"age"
: 30 }
>
|
使用limit来返回前两个记录:
1
2
3
4
|
> cursor.limit(2)
{
"_id"
: ObjectId(
"54ace1394ba07ed75df68f90"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 28 }
{
"_id"
: ObjectId(
"54ace753eab1d0ba4abb48ab"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 30 }
>
|
或者使用skip来跳过前3个记录:
1
2
3
4
5
|
> cursor.skip(3)
{
"_id"
: ObjectId(
"54ace781eab1d0ba4abb48ad"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 6 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace785eab1d0ba4abb48ae"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 5 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace789eab1d0ba4abb48af"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 7 },
"age"
: 30 }
>
|
或者使用sort指定键值排序:
1
2
3
4
5
6
7
|
> cursor.
sort
({
"age"
:1})
{
"_id"
: ObjectId(
"54ace1394ba07ed75df68f90"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 28 }
{
"_id"
: ObjectId(
"54ace753eab1d0ba4abb48ab"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
},
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace777eab1d0ba4abb48ac"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 10 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace781eab1d0ba4abb48ad"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 6 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace785eab1d0ba4abb48ae"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 5 },
"age"
: 30 }
{
"_id"
: ObjectId(
"54ace789eab1d0ba4abb48af"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 7 },
"age"
: 30 }
|
综合使用sort/limit/skip,当然可以调整顺序得到不同的结果:
1
2
3
|
> cursor.
sort
({
"name.comment"
:1}).skip(2).limit(1)
{
"_id"
: ObjectId(
"54ace785eab1d0ba4abb48ae"
),
"name"
: {
"firstname"
:
"joe"
,
"lastname"
:
"schome"
,
"comment"
: 5 },
"age"
: 30 }
>
|
游标生命周期:
游标会消耗内存和其他资源,游标使用完后会释放资源以供数据库它用;游标会在以下情况终止,
(1)游标完成匹配结果的迭代后,它会清楚自身;
(2)客户端的游标已经不再作用域内,驱动程序回向服务器发送一条特别的消息,让其销毁;
(3)游标在十分钟内没有使用,游标自动销毁;
本文转自 bannerpei 51CTO博客,原文链接:http://blog.51cto.com/281816327/1600283,如需转载请自行联系原作者