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

134
Views
Get the documents of order id 1 that are not in order id 2 MongoDB

I have this set of documents

{_id: ObjectId(""),orderid:1,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:1,productName:"Xiaomi 11"}
{_id: ObjectId(""),orderid:1,productName:"Pocophone F1"}
{_id: ObjectId(""),orderid:1,productName:"Samsung S22"}
{_id: ObjectId(""),orderid:2,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:2,productName:"Xiaomi 11"}

I am trying to get the product names that are in order 1 but not in order 2, my mongodb query was:

{orderid:{$eq:orderid-1,$ne:orderid}}

but it does not work, then I was trying with an aggregate op like:

{
    $match: {orderid:{$gte:orderid-1}} //this is because allways a will try to get the products name in max orderid - 1 to get that resutl with the last 2 orders
    $group:{
       _id: {productname: '$productName'}
       orders:{$push:'$orderid'}
       total:{$sum:1}
    }
    //Then here i'm trying to get just de maxorderid-1 docs that just have total equal 1 but i cant achive the result.
}

Thanks you so much for your support and answers.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If I've understood correctly you can try something like this:

  • First $group by productName and store orderids in an array
  • The $match by values in the array: $and condition where exists 1 and not 2.
  • And then rebuild the objects using $unwind and $project with the axuliar field root saved in the $group stage
db.collection.aggregate([
  {
    "$group": {
      "_id": "$productName",
      "orderids": {
        "$push": "$orderid"
      },
      "root": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$match": {
      "$and": [
        {
          "orderids": 1
        },
        {
          "orderids": {
            "$ne": 2
          }
        }
      ]
    }
  },
  {
    "$unwind": "$root"
  },
  {
    "$project": {
      "_id": "$root._id",
      "orderid": "$root.orderid",
      "productName": "$root.productName"
    }
  }
])

Example here

Also, if you only want the productName, that value is stored in the id of the group, soy uo don't need the last two stages. Like this example

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!