简体   繁体   中英

mongodb - using .limit() seems to result in no documents in cursor/variable

I am trying to retrieve a limited cursor with only 2 documents, but my variable is always empty if I use limit().

Can anyone explain the behavior shown? I'm just not sure what I am doing wrong.

> myCursor = db.raw.incomingdata.find({'dat_type': 'foo'}, {'_id': 1}).sort({'_id' : 0}).limit(2);
{ "_id" : ObjectId("51a8b24d02292b2fb3000001") }
{ "_id" : ObjectId("519fd10a02292b0ede000002") }
> myCursor
>

note that 'myCursor' returns nothing, when I expected it to have 2 objects.

> myCursor2 = db.raw.incomingdata.find({'dat_type': 'foo'}, {'_id': 1}).sort({'_id' : 0}); 
{ "_id" : ObjectId("519fd10a02292b0ede000002") } 
{ "_id" : ObjectId("519fd10602292b0ede000001") } 
{ "_id" : ObjectId("519fcc3402292b6e0e000002") } 
{ "_id" : ObjectId("519fcc3002292b6e0e000001") } 
{ "_id" : ObjectId("519fca5802292b60d8000001") } 
{ "_id" : ObjectId("519e81dd02292b6f50000002") } 
{ "_id" : ObjectId("519e81d902292b6f50000001") } 
{ "_id" : ObjectId("519e800e02292b66aa000001") } 
{ "_id" : ObjectId("519e7b1a02292b4851000001") } 
(etc., etc.) 
Type "it" for more
> myCursor2 
{ "_id" : ObjectId("519fd10a02292b0ede000002") } 
{ "_id" : ObjectId("519fd10602292b0ede000001") } 
{ "_id" : ObjectId("519fcc3402292b6e0e000002") } 
{ "_id" : ObjectId("519fcc3002292b6e0e000001") } 
{ "_id" : ObjectId("519fca5802292b60d8000001") } 
{ "_id" : ObjectId("519e81dd02292b6f50000002") } 
{ "_id" : ObjectId("519e81d902292b6f50000001") } 
{ "_id" : ObjectId("519e800e02292b66aa000001") } 
{ "_id" : ObjectId("519e7b1a02292b4851000001") } 
(etc., etc.) 

How do I maintain the data from the first call, like it is in the second call?

This is because you already "executed" your cursor - and it's done.

Try adding

var cursor = ...

Now you will see the documents - but only once!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM