您好,登錄后才能下訂單哦!
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 } >
游標生命周期:
游標會消耗內存和其他資源,游標使用完后會釋放資源以供數據庫它用;游標會在以下情況終止,
(1)游標完成匹配結果的迭代后,它會清楚自身;
(2)客戶端的游標已經不再作用域內,驅動程序回向服務器發送一條特別的消息,讓其銷毀;
(3)游標在十分鐘內沒有使用,游標自動銷毀;
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。