我只想为付款订单过滤特定用户的费用。这是我的架构:
var PaymentOrderSchema = new Schema({
name: {type: String, required: true},
description: {type: String},
amount: {type: Number},
charges: [{type: Schema.Types.ObjectId, ref: 'Charge'}],
},
var ChargeSchema = new Schema({
amount: {type: Number},
user: {type: Schema.Types.ObjectId, ref: 'User'},
status: {type: String},
description: {type: String},
creation_date:{type: Date}
}
我正在尝试使用汇总,但无法过滤费用。当我使用$ ne而不是$ eq时,它确实会退还给我费用,因此我知道自己的做法正确。这是我的实际代码:
const paymentOrder = await PaymentOrder.aggregate([
{$match: {'_id': mongoose.Types.ObjectId(req.query.payment_order_id)}},
{$project: {
charges: {$filter: {
input: '$charges',
as: 'charge',
cond: {$eq: ['$$charge.user._id', mongoose.Types.ObjectId(req.user._id)]}
}}
}}
]);
谢谢!
答案 0 :(得分:1)
如果我理解您的要求正确,那么我们可以在管道中使用$ lookup
类似的东西
db.paymentOrder.aggregate([
{
$match: {
_id: ObjectId("5a934e000102030405000003") // replace this hard-coded objectId with mongoose.Types.ObjectId(req.query.payment_order_id)
}
},
{
$lookup: {
from: "charge",
let: {
chargeIds: "$charges"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$user",
"userId1" // replace this with mongoose.Types.ObjectId(req.user._id)
]
}
}
}
],
as: "charges"
}
}
])
希望有帮助
答案 1 :(得分:1)
聚合在数据库服务器上运行,而引用由客户端的驱动程序扩展,因此管道中实际看到的值为
DBRef("User",ObjectId(...),"DatabaseName")
可以像访问对象一样访问
{"$ref":"User", "$id":ObjectId(...), "$db":"DatabaseName"}
但这会带来另一个问题:字段名称不允许以$
开头,因此会引发错误:
{$eq:["$$charge.user.$id",mongoose.Types.ObjectId(req.user._id)]}
因此,您可以跳过聚合中的这一步骤,然后将文档放回到猫鼬中进行填充,或者如果只需要在$id
上进行匹配,则可以使用$objectToArray
来中断DBRef向下,这样您就可以匹配:
{$match: {'_id': mongoose.Types.ObjectId(req.query.payment_order_id)}},
{$unwind: "$charges"},
{$addFields: {charges:{$objectToArray:"$charges"}}},
{$match: {charges:{
$elemMatch:{k:"$id",v:mongoose.Types.ObjectId(req.user._id}
}}},
{$group:{_id:"$_id", charges:{$push:{$arrayToObject("$charges"}}}}}
这使您获得了可以由驱动程序扩展的DBRef,但这与_id
文档的charges
相匹配,这可能不是您想要的。
但是,一旦您拥有费用凭证的_id
,就可以使用$lookup
然后对其进行过滤,但是我们还必须将user
作为DBref来处理:
{$match: {'_id': mongoose.Types.ObjectId(req.query.payment_order_id)}},
{$unwind: "$charges"},
{$addFields: {chargeId:{$filter:{
input:$objectToArray:"$charges"
cond:{$eq:["$$this.k","$id"]}
}}}},
{$lookup:{
from:"charge",
localField:"$chargeId.v",
foreignField:"$_id",
as: charges
}},
{$unwind:"$charges"},
{$addField:{chargeUser:{$filter:{
input:{$objectToArray:"$charges.user"},
cond:{$eq:["$$this.k","$id"]}
}}}},
{$match: {"chargeUser.v":mongoose.Types.ObjectId(req.user._id)}},
{$project:{
chargeUser:0,
chargeId:0
},
{$group:{
_id:"$_id",
document:{$first:"$$ROOT"},
charges:{$push:"$charges"}
}},
{$addFields:{"document.charges":"$charges"}},
{$replaceRoot:{newRoot:"$document"}}