我希望按ID(56e641d4864e5b780bb992c6和56e65504a323ee0812e511f2)显示产品,并在扣除减价后显示价格(如果有).
我可以使用聚合计算最终价格,但这会返回集合中的所有文档,如何使其仅返回匹配ID
"_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)
Run Code Online (Sandbox Code Playgroud)
这是我的疑问
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) …Run Code Online (Sandbox Code Playgroud)