skip to Main Content

Sample

{rating: 2}
{rating: 3}
{rating: 5}
......


What I am trying to do :

var result=db.movies_pipeline.aggregate([{$group: {_id:null, "result": {$avg:"rating"} } }]).
// output : [ { _id: null, result: 6.713884823964879 } ]

db.movies_pipeline.find({
    $expr: {
      $lt: [
        "rating"
        ,
        result[0].result
      ]
    }
  },
  { "rating":"$critic_review.rating"}
)

This gives an error:

 Cannot read properties of undefined (reading 'result')

Is is mongo shell not an really programming language?

I have checked the result of aggreation:

-> typeof result
object

How can I read the value I want from this object and use it in another query?

2

Answers


  1. Chosen as BEST ANSWER

    @Charchit Kapoor is absolutely correct! I just want add one more solution for learning purpose - map (callback function) can also help you convert the result to the one you want:

    db.movies_pipeline.aggregate([
        { 
            $group: { _id: null, "result": { $avg: "$rating" } } 
        }
    ]).map(
        function(doc){
            print(doc.result)
            var res = db.movies_pipeline.find({ //find
                $expr: {
                  $lt: [
                    "$rating"
                    ,
                    doc.result
                  ]
                }
              },
              { "rating":"$critic_review.rating"}
            )
            print(res)
        }
    )
    
    

  2. aggregate function returns a cursor. You need to store the result as an array, by using the toArray method. Like this:

    var result=db.movies_pipeline.aggregate([
       {$group: {_id:null, "result": {$avg:"rating"} } }]).toArray()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search