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.
Si he entendido bien puedes probar algo como esto:
$group por productName y almacenar orderids en una matriz$match por valores en la matriz: $and condición donde existe 1 y no 2 .$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