I want to show products using identifiers ( 56e641d4864e5b780bb992c6 and 56e65504a323ee0812e511f2 ) and show the price after subtraction with a discount, if available.
I can calculate the final price using an aggregate, but this returns the whole document in the collection, how to make it return only matches ids
"_id" : ObjectId("56e641d4864e5b780bb992c6"), "title" : "Keyboard", "discount" : NumberInt(10), "price" : NumberInt(1000) "_id" : ObjectId("56e65504a323ee0812e511f2"), "title" : "Mouse", "discount" : NumberInt(0), "price" : NumberInt(1000) "_id" : ObjectId("56d90714a48d2eb40cc601a5"), "title" : "Speaker", "discount" : NumberInt(10), "price" : NumberInt(1000)
this is my request
productModel.aggregate([ { $project: { title : 1, price: { $cond: { if: {$gt: ["$discount", 0]}, then: {$subtract: ["$price", {$divide: [{$multiply: ["$price", "$discount"]}, 100]}]}, else: "$price" } } } } ], function(err, docs){ if (err){ console.log(err) }else{ console.log(docs) } })
and if I add this request to $in , it returns an empty array
productModel.aggregate([ { $match: {_id: {$in: ids}} }, { $project: { title : 1, price: { $cond: { if: {$gt: ["$discount", 0]}, then: {$subtract: ["$price", {$divide: [{$multiply: ["$price", "$discount"]}, 100]}]}, else: "$price" } } } } ], function(err, docs){ if (err){ console.log(err) }else{ console.log(docs) } })
mongodb mongoose mongodb-query aggregation-framework
Muhammad Fasalir Rahman
source share