Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-33107

Incorrect result while using pipeline with skip and limit

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.6.2
    • Component/s: Aggregation Framework
    • Labels:
      None
    • Environment:
      db.version() --> 3.6.2
      OS: MacOS High Sierra 10.13.1
    • ALL
    • Hide

      STR:
      1. Create new test collection
      2. Insert documents from the test.json file
      3. Run the following query:

      
      db.getCollection('test').aggregate([
          {
              "$match": {
                  "$and": [ { "status": { "$eq": "active" } } ]
              }
          },
          { "$sort": { "status": 1 } },
          { "$skip": 4 },
          { "$limit": 2 }
      ])
      
      

      Expected result: the documents with ids 6 and 7 are returned as in chained query

      
      db.getCollection('test')
          .find({
                  "$and": [ { "status": { "$eq": "active" } } ]
          })
          .sort({ "status": 1 })
          .skip(4)
          .limit(2)
      

      Actual result: the documents with ids 3 and 5 are returned

      Show
      STR: 1. Create new test collection 2. Insert documents from the test.json file 3. Run the following query: db.getCollection( 'test' ).aggregate([ { "$match" : { "$and" : [ { "status" : { "$eq" : "active" } } ] } }, { "$sort" : { "status" : 1 } }, { "$skip" : 4 }, { "$limit" : 2 } ]) Expected result: the documents with ids 6 and 7 are returned as in chained query db.getCollection( 'test' ) .find({ "$and" : [ { "status" : { "$eq" : "active" } } ] }) .sort({ "status" : 1 }) .skip(4) .limit(2) Actual result: the documents with ids 3 and 5 are returned

      I was trying to use an aggregation pipeline in the following order:
      match -> sort -> skip(4) -> limit(2)

      In my case:
      1. Match step returned 6 documents
      2. Sort step sorts data, but they all have the same value in the sorted column
      3. Skip step skips first 4 documents
      4. Limit step limits the result to 2 documents.

      I expected to see last 2 documents from the match result, but the query returned 2-nd and 4-th documents from the match result. If I set a limit to 3, then everything works as expected (I receive last 2 documents). The other way to get a correct result is to add an _id : 1 as the last sort column in sort step or exclude sort step at all.

      If I use simple chaining like .find().sort().skip().limit() it works correct too.

        1. test.json
          0.4 kB
          Yaroslav

            Assignee:
            mark.agarunov Mark Agarunov
            Reporter:
            iamyardem Yaroslav
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: