error in script not seen when run in shell

Michael shared this problem 56 days ago
Solved

Hi

I'm relatively new with mongo and nosqlbooster. I've been doing a mongo university course on aggregation. One of the labs has the student put their aggregation pipeline through their provided javascript function to emit an altered result to submit (presumably to make the answer not so obvious).

The problem I had is when I ran their script together with my aggregation pipeline via nosqlbooster (Mac without mongo db or tools installed), I got an error: "Cannot read property 'pop' of undefined".

However when I run the same thing through command-line mongo shell (on PC), there's no problem (I see the correct answer emitted).

In looking at their js code, it appears that this line raises the issue.

let { _id, title, rated } = resultsExplain.stages.pop()["$project"]
Below is the code (I've trimmed the $match part). I'm not sure what else I can offer to help explain or clarify the error. I feel there is some difference between mongo's native command-line shell (shell version: 4.0.10 on Win10) and nosqlbooster (using 5.1.14 on Mac). Any tips appreciated. Thanks.

var pipeline = [
    {
        $match: {
            genres: { $nin: ['Crime', 'Horror'] },
            rated: { $in: ['G', 'PG'] }
        }
    },
    {
        $project: { _id: 0, rated: 1, title: 1 }
    }
]

var validateLab2 = pipeline => {
  let aggregations = db.getSiblingDB("aggregations")
  if (!pipeline) {
    print("var pipeline isn't properly set up!")
  } else {
    try {
      let resultsExplain = aggregations.movies.aggregate(pipeline, {
        explain: true
      })
      let result = aggregations.movies.aggregate(pipeline).toArray().length
      let data = 0
      while (result != 1) {
        data++
        result = result % 2 === 0 ? result / 2 : result * 3 + 1
      }
      let { _id, title, rated } = resultsExplain.stages.pop()["$project"]
      return title && rated && !_id
        ? print("Answer is", data)
        : print("Your $project stage doesn't seem correct")
    } catch (e) {
      print(e.message)
    }
  }
}

validateLab2(pipeline)

Comments (2)

photo
1

Thank you for your bug report. We will fix the explain result bug in the next update. In NoSQLBooster, the "aggregate" method always returns a cursor, while MongoShell 4.0 returns result in object directly when the option "explain" is true.

There is a work-around solution. Please replace the following statements.

let resultsExplain = aggregations.movies.aggregate(pipeline, {
        explain: true
      }).toArray()[0];  //add  toArray()[0]

photo
1

Resolved in 5.2.1