【MongoDB学习笔记19】MongoDB的游标和查询选项
MongoDB使用游标来处理find查询到的结果文档集;
游标的使用实例:
> 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来返回前两个记录:
> 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个记录:
> 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指定键值排序:
> 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,当然可以调整顺序得到不同的结果:
> cursor.sort({"name.comment":1}).skip(2).limit(1) { "_id" : ObjectId("54ace785eab1d0ba4abb48ae"), "name" : { "firstname" : "joe", "lastname" : "schome", "comment" : 5 }, "age" : 30 } >
本文出自 “缘随心愿” 博客,请务必保留此出处http://281816327.blog.51cto.com/907015/1600283
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。