gpt4 book ai didi

mongodb - Mongoose 聚合 $match 不匹配 id

转载 作者:IT老高 更新时间:2023-10-28 13:08:09 28 4
gpt4 key购买 nike

我想按 ID(56e641d4864e5b780bb992c656e65504a323ee0812e511f2)显示产品,并在可用折扣后显示价格。

我可以使用聚合来计算最终价格,但这会返回集合中的所有文档,如何让它只返回匹配的 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)
}
})

最佳答案

您的 ids 变量将由“字符串”而不是 ObjectId 值构成。

Mongoose 在常规查询中将 ObjectId 的字符串值“自动转换”为正确的类型,但 does not happen in the aggregation pipeline ,如问题 #1399 中所述。

相反,您必须进行正确的强制转换才能手动输入:

ids = ids.map(function(el) { return mongoose.Types.ObjectId(el) })

然后你可以在你的流水线阶段使用它们:

{ "$match": { "_id": { "$in": ids } } }

原因是因为聚合管道“通常”会改变文档结构,因此 mongoose 不会假定“模式”适用于任何给定管道阶段的文档。

有争议的是,当它是 $match 阶段时,“第一个”管道阶段应该这样做,因为确实文档没有被更改。但现在情况并非如此。

任何可能是“字符串”或至少不是正确 BSON 类型的值都需要手动转换才能匹配。

关于mongodb - Mongoose 聚合 $match 不匹配 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193289/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com