月鵝集合$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 關注
- 746 瀏覽
添加回答
舉報
0/150
提交
取消