月鹅集合$Match与id的不匹配我想按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)
}
})
3 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
ids
ObjectId
ObjectId
ids = ids.map(function(el) { return mongoose.Types.ObjectId(el) })
{ "$match": { "_id": { "$in": ids } } }
$match
ITMISS
TA贡献1871条经验 获得超8个赞
const castUserId = (userId) => mongoose.Types.ObjectId(userId)
- 3 回答
- 0 关注
- 699 浏览
添加回答
举报
0/150
提交
取消