Limit (1) .skip (1): Why is it returning a second document and not nothing?

I am new to mongodb, so please bear with me. I searched for it, but could not find a convincing answer. I understand that the following should limit n1 documents as a result and skip n2 from this.

>db.mycol.find({},{"title":1}).limit(n1).skip(n2)

Why does the following query return the second document in the collection? Can't he return anything? (Limit one gives the first document and skips that leaves us nothing).

>db.mycol.find({},{"title":1}).limit(1).skip(1)
+4
source share
3 answers

What do you want to do if you put limitup skip?

If you are restricting items N, then skipK

this is logically equivalent to skipping Kand limit N-K.

, .

.

+3

, n1 n2 .

, . :

  • , .sort(), .skip() .limit()
  • , , , .
  • .sort(),
  • .skip().
  • , .limit()

:

> db.bg.insert({a:1})
WriteResult({ "nInserted" : 1 })
> db.bg.insert({a:2})
WriteResult({ "nInserted" : 1 })
> db.bg.insert({a:3})
WriteResult({ "nInserted" : 1 })
> db.bg.insert({a:4})
WriteResult({ "nInserted" : 1 })
> db.bg.find()
{ "_id" : ObjectId("56889a8a32a39e5b2c96acb5"), "a" : 1 }
{ "_id" : ObjectId("56889a8d32a39e5b2c96acb6"), "a" : 2 }
{ "_id" : ObjectId("56889a9032a39e5b2c96acb7"), "a" : 3 }
{ "_id" : ObjectId("56889ad332a39e5b2c96acb8"), "a" : 4 }

// According to your logic, this query would be empty
// (Only one doc returned, and of that returned one skipped)
// But it bears a result…
> db.bg.find().sort({a:-1}).limit(1).skip(1)
{ "_id" : ObjectId("56889a9032a39e5b2c96acb7"), "a" : 3 }

// …actually the same result when switching the place of the clauses
> db.bg.find().sort({a:-1}).skip(1).limit(1)
{ "_id" : ObjectId("56889a9032a39e5b2c96acb7"), "a" : 3 }

// Even when we put the sort clause to the end.
// If the query optimizer would not have enforced the order mentioned
// we would have natural order as in the default query,
// then skip 1 (we would be at {a:2}),and limit to that document, making
// the sort clause useless.
// But, as you can see, it is the same result as before
> db.bg.find().skip(1).limit(1).sort({a:-1})
{ "_id" : ObjectId("56889a9032a39e5b2c96acb7"), "a" : 3 }
+1

https://docs.mongodb.org/v3.0/reference/method/cursor.skip/

NOTE
You must apply cursor.skip() to the cursor before retrieving any documents from the database.

While the limit applies when querying for results.

Thus, the search finds all documents that meet the criteria, and Skip is applied until the documents and the number of documents specified in the limit are received.

0
source

Source: https://habr.com/ru/post/1622563/


All Articles