我想通过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)
这是我的查询
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)
}
})
如果我加上这个$in
查询,它会返回空数组
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)
}
})
.find()
可以使用Schema
,当然_id
字段的默认类型是ObjectId
。聚合管道不使用Schema
,这一点我已经解释过了。 - Blakes Sevenconst castUserId = (userId) => mongoose.Types.ObjectId(userId)
,现在我很高兴。 - timebandit$in
是否比精确匹配慢的可能性有多大? - shramee