Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Ho use $sum (aggregation) for array of object and check greater than for each sum

My document structure is as follow :

{
    "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"),
    "cust_name" : "Anuj Kumar",
    "product" : [
        {
            "prod_name" : "Robot",
            "price" : 15000
        },
        {
            "prod_name" : "Keyboard",
            "price" : 65000
        }
    ],
    "order_date" : ISODate("2022-02-22T00:00:00Z"),
    "status" : "processed",
    "invoice" : {
        "invoice_no" : 111,
        "invoice_date" : ISODate("2022-02-22T00:00:00Z")
    }
}

How to do the following query... List the details of orders with a value >10000.

I want to display only those objects whose sum of prices is greater than 10000

I try this

db.order.aggregate([{$project : {sumOfPrice : {$sum : "$product.price"} }}])

Output

{ "_id" : ObjectId("621ccb5ea46a9e41768e0ba8"), "sumOfPrice" : 80000 }
{ "_id" : ObjectId("621ccba9a46a9e41768e0ba9"), "sumOfPrice" : 16500 }
{ "_id" : ObjectId("621ccbfaa46a9e41768e0baa"), "sumOfPrice" : 5000 }

I want to check this sumOfPrice is greater than 10000 or not and display those order full object.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can just add a $match stage right after that checks for this conditions, like so:

db.collection.aggregate([
  {
    $addFields: {
      sumOfPrice: {
        $sum: "$product.price"
      }
    }
  },
  {
    $match: {
      sumOfPrice: {
        $gt: 10000
      }
    }
  }
])

Mongo Playground

over 4 years ago · Santiago Trujillo Report

0

You can also use $expr operator with the find query as:

db.order.find({
    $expr: {
        $gt: [ {$sum: '$product.price'}, 10000 ]
    }
})

Mongo Playground

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!