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

171
Views
MongoDB: Find sets of documents that have same key value

I'm searching a collection based on some conditions:

const orders = Order.find({ status: 'ACTIVE', isInFlux: true  });

Then as I loop through every one of those documents I search Orders again with:

Order.find({ userId: order.userId, status: 'ACTIVE', inFlux: true })

Then I check to see if there are multiple orders belonging to this user that meet these conditions.

Is there a way I can modify my query to get these documents in one shot without having to loop through all of them or possibly an aggregation that would help me?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Looks like you're just trying to conditionally group orders by userID. This will probably do the trick:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$user",
      "orders": {
        "$push": {
          "$cond": [
            {
              $and: [
                {
                  "$eq": [
                    "$isInFlux",
                    true
                  ]
                },
                {
                  "$eq": [
                    "$status",
                    "active"
                  ]
                }
              ]
            },
            "$$ROOT",
            "$$REMOVE"
          ]
        }
      }
    }
  }
])

Playground: https://mongoplayground.net/p/c8MGdZsjMlJ

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!