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

129
Views
Obtenga los documentos del ID de pedido 1 que no están en el ID de pedido 2 MongoDB

tengo este conjunto de documentos

 {_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"}

Estoy tratando de obtener los nombres de los productos que están en orden 1 pero no en orden 2, mi consulta mongodb fue:

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

pero no funciona, entonces estaba intentando con una operación agregada como:

 { $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. }

Muchas gracias por su apoyo y respuestas.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Si he entendido bien puedes probar algo como esto:

  • Primero $group por productName y almacenar orderids en una matriz
  • La $match por valores en la matriz: $and condición donde existe 1 y no 2 .
  • Y luego reconstruya los objetos usando $unwind y $project con la root del campo axuliar guardada en la etapa de $group
 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" } } ])

Ejemplo aquí

Además, si solo desea el nombre del productName , ese valor se almacena en la id del grupo, por lo que no necesita las dos últimas etapas. Como este ejemplo

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!