Home > OS >  How to store the aggregation result to a var in mongo shell and use it again
How to store the aggregation result to a var in mongo shell and use it again

Time:09-01

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?

CodePudding user response:

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()

CodePudding user response:

@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)
    }
)

  • Related