中子文档的参考模型的字段名称"/>
Mongodb集合管道,用于匹配集合中子文档的参考模型的字段名称
我有两个集合,一个是产品,另一个是商店
prouduct1 = {
name: "chair",
code: 034,
};
product2 = {
name: "table",
code: 035,
};
在物料输入期间,将使用以下模式更新商店模型
goodsReceipt = {
invoicenumber: 2,
products: [
{ product: "ObjectId(product1)", qty: 15 },
{ product: "ObjectId(product2)", qty: 20 },
],
};
现在,我想遍历整个商店的寄存器并匹配产品1的ID,然后找出所有数量的总和。
回答如下:您可以在下面的聚合中使用
import mongoose from "mongoose";
db.stores.aggregate([
{ $match: { "products.product": mongoose.Types.ObjectId(productId) }},
{ $unwind: "$products" },
{ $match: { "products.product": mongoose.Types.ObjectId(productId) }},
{ $group: {
_id: null,
qty: { $sum: "$products.qty" }
}}
])
更多推荐
Mongodb集合管道,用于匹配集合中子文档的参考模型的字段名称
发布评论