spacearound
spacearound

Reputation: 51

How to perform grouping in mongodb like lodash chain and groupby

I have a lodash function which group and return an array as below

  [{ key: '00001',
    amount: 135,
    request: [ false, false ] }]

I want to check if the request contains some value. Is there any possibility i can perform this mongoDB aggregate. So far i can only group the data with... I am using mongoose

  $group: {
        _id: "$key",
        name: { $first: "$request" },
        count: { $sum: 1 }, 
        totalValue: { $sum: "$amount" }, 
       },

The sample document


  [{ request: false,
    key: '00001',
    amount: 17,
    __v: 0 },
  { request: false,
    _id: 5f536fb1b05c47f7d87acb8d,
    key: '00002',
    amount: 41,
    __v: 0 },
  { request: false,
    _id: 5f536fb1b05c47f7d87acb8e,
    key: '00002',
    amount: 29,
    __v: 0 },
  { request: false,
    _id: 5f536fb1b05c47f7d87acb8f,
    key: '00001',
    amount: 312,
    __v: 0 },
  { request: true,
    _id: 5f536fb1b05c47f7d87acb90,
    key: '00002',
    amount: 120,
    __v: 0 }]

Thanks in advance!

Upvotes: 1

Views: 331

Answers (1)

turivishal
turivishal

Reputation: 36134

You can try,

  • $group to push request in request field
  • $match to check condition using $anyElementTrue
db.collection.aggregate([
  {
    $group: {
      _id: "$key",
      request: { $push: "$request" },
      count: { $sum: 1 },
      amount: { $sum: "$amount" }
    }
  },
  {
    $match: {
      $expr: {
        $eq: [false, { $anyElementTrue: "$request" }]
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions