Home > front end >  MongoDB aggregate function with find function
MongoDB aggregate function with find function

Time:04-06

I am using coffeescript with nodejs to query monogodb data but for some custom data i need to perform aggregate function on my collection but using Session.aggregate(query) in the code is giving me error like not pipeline operator $and. So, i was thinking if can we integrate the aggregate func with the find method of monoogo.. any clue?

Query which i have defined in coffee-script is:

query = {
          $and : [ 
            { $match : { product: req.body.product } },
            { $project: { "_id": 1, totalHourSpent:{ $subtract: [ "$end_date", "$start_date" ] }}}
          ]
  }

Working fine while executing in the mongo shell but giving error while fetching the data with the coffee-script.

CodePudding user response:

You got the syntax for aggregates in MongoDB wrong.

It should be an array, not an object passed to the aggregate method. The mongoose documentation shows this in an example and links you to the official mongo documentation as it's the same syntax.

You cannot use $and as a top level operator in an aggregate. You can use it inside a $match operator. But you cannot use it to combine a $match and $project. These are two separate steps in the pipeline and are done in sequence. There is no need for an $and operator in your query.

query = [
  {  
    $match : { 
      product: req.body.product 
      } 
  }, {
    $project: { 
      "_id": 1, 
      totalHourSpent: { 
        $dateDiff: [ "$end_date", "$start_date" ] 
      }
    }
  }
]

If this doesn't work, then please provide us with a Minimal Reproducible Example containing your Schema, an example document in the collection, the code surrounding this aggregate call and the request data being sent to the server.

CodePudding user response:

query = [ { $match : { product: req.body.product } },
          { $project: { "_id": 1, totalHourSpent:{ $subtract: [ "$end_date", "$start_date" ] }}}          
  ]
  Session.aggregate(query)
  .exec((err, session) ->
    if err
      res.json err
      return 
    
    count = 0
    session.forEach () ->
        count = count   1

    res.json count

count var just to check the no of response which i get but it returns 0 always.

NOTE: The query is working correctly in the Robo3T when running directly.

  • Related