gpt4 book ai didi

node.js - Mongoose - 如何按属性值查询子文档

转载 作者:可可西里 更新时间:2023-11-01 09:43:27 25 4
gpt4 key购买 nike

我正在尝试获取一系列未付款订单。订单子(monad)文档有一个属性 isPaid 定义订单是否已经支付。

在我看来,我只想显示尚未支付的订单。

这是我的架构:

var order = new Schema({
content: [{
product: {type: String, required: true},
quantity: {type: Number},
vatRate: {type: Number, required: true},
price: {type: Number}
}],
isPaid: {type: Boolean, default: false},
number: {type: Number}
});

var clientSchema = new Schema({
[...]
information: {
code: {type: String, required: true},
name: {type: String, required: true}
},
orders: [order],
[...]
});

我开始了,但没有成功

clientModel.find(
{
"information.code": clientCode,
"orders.isPaid": false
}, function (err, client) { ... });

然后,我做了很多尝试,$all$elemMatch 都没有成功。大多数时候,它会返回所有已付款或未付款的订单。我不知道为什么。我需要一些帮助,拜托:)

最佳答案

您可以采用的一种方法是使用 aggregation framework得到想要的数组。考虑以下首先使用 $match 的管道运算符过滤将进入下一阶段的文档,$project步。这只会生成所需的订单数组,该数组将使用 $filter 进行过滤以及申请条件过滤器使用比较运算符 $eq在子文档 isPaid 上。

最后管道看起来像这样:

const pipeline = [
{ '$match': {
'information.code': clientCode,
'orders.isPaid': false
} },
{ '$project': {
'orders': {
'$filter': {
'input': '$orders',
'cond': {
'$eq': ['$$this.isPaid', false]
}
}
}
} }
]

或者如果MongoDB服务器版本不支持$filter (老司机),初始匹配后的下一步是 $unwind .

这一步从输入文档中解构订单数组字段,为每个元素输出一个文档。每个输出文档都是用元素替换数组字段值的输入文档。

下一步使用 $match运算符然后对解构的子文档进行进一步过滤,然后将其分组(使用 $group )标识符 _id 表达式并应用累加器表达式 $push (在订单子(monad)文档)到返回所需数组的每个组。

const pipeline = [
{ '$match': {
'information.code': clientCode,
'orders.isPaid': false
} },
{ '$unwind': '$orders' },
{ '$match': {
'orders.isPaid': false
} },
{ '$group': {
'_id': '$_id',
'orders': {
'$push': '$orders'
}
} }
]

clientModel.aggregate(pipeline).exec(function (err, res){
if (err) return handleError(err);
console.log(res); // [ { orders: [...] } ]
});

或者使用 aggregation pipeline builder :

clientModel.aggregate()
.match({'information.code': clientCode, 'orders.isPaid': false})
.project({
'orders': {
'$filter': {
'input': '$orders',
'cond': {
'$eq': ['$$this.isPaid', false]
}
}
}
})
.exec(function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { orders: [...] } ]
});

或旧版本

clientModel.aggregate()
.match({'information.code': clientCode, 'orders.isPaid': false})
.unwind('orders')
.match({'orders.isPaid': false })
.group({'_id': '$_id', 'orders': { '$push': '$orders' } })
.select('-_id orders')
.exec(function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { orders: [...] } ]
});

关于node.js - Mongoose - 如何按属性值查询子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740932/

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