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

Cursor array access does not work reliably

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.3.5, 3.4.3
    • Component/s: JavaScript, Shell
    • None
    • Fully Compatible
    • ALL
    • Hide
      • Execute prepare.js
      for (i=1; i<=2500; i++) {
          db.items.insert({_id: i});
          if (i % 2) {
              db.reviews.insert({ item_id: i });
          }
      }
      

      Note that a review is created for every odd item.

      • Execute find_items_without_reviews.js. This script should return a list with all even numbers from 2 to 2500 because exactly the even items do not have an associated review. However, the actual result is [2, 4, 6, ..., 1998, 2000, 2001, 2002, 2003, ..., 2499, 2500], i.e. starting with 2001 also all odd numbers are returned.
      Show
      Execute prepare.js for (i=1; i<=2500; i++) { db.items.insert({_id: i}); if (i % 2) { db.reviews.insert({ item_id: i }); } } Note that a review is created for every odd item. Execute find_items_without_reviews.js. This script should return a list with all even numbers from 2 to 2500 because exactly the even items do not have an associated review. However, the actual result is [2, 4, 6, ..., 1998, 2000, 2001, 2002, 2003, ..., 2499, 2500] , i.e. starting with 2001 also all odd numbers are returned.
    • Platforms 2017-08-21

      The MongoDB shell supports accessing a cursor's elements via array access, without first converting the cursor into an array: db.items.find(...)[0]
      However, this might return 'undefined' even when the cursor actually contains elements.
      I attached a script that demonstrates the issue.

      Some notes:

      • The problem disappears when using the toArray-function.
      • Direct array access on a cursor seems to be not documented. However, because it is so intuitive and works in most cases, it is probably often used.
      • When running into the issue, the shell seems to be in an inconsistent state. As the 'inconsistent.js' script demonstrates, an if-clause with identical 'then' and 'else' branches might return different results depending on the condition.

        1. find_items_without_reviews.js
          0.3 kB
          Martin Altmayer
        2. inconsistent.js
          0.6 kB
          Martin Altmayer
        3. prepare.js
          0.1 kB
          Martin Altmayer

            Assignee:
            mark.benvenuto@mongodb.com Mark Benvenuto
            Reporter:
            martinaltmayer Martin Altmayer
            Votes:
            0 Vote for this issue
            Watchers:
            11 Start watching this issue

              Created:
              Updated:
              Resolved: