Mongodb集合管道,用于匹配集合中子文档的参考模型的字段名称

编程入门 行业动态 更新时间:2024-10-09 08:30:43

Mongodb集合管道,用于匹配集合<a href=https://www.elefans.com/category/jswz/34/1761451.html style=中子文档的参考模型的字段名称"/>

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集合管道,用于匹配集合中子文档的参考模型的字段名称

本文发布于:2024-05-07 04:24:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中子   字段   管道   模型   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!