使用mongo db在MongoDB中的另一个集合上查找数组元素聚合查找

r3i60tvu  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(80)

我在Mongodb中有两个集合。它们彼此相关。
第一集合结构如下:

semiproducts = [
  {
    _id: "64afad9eda7e337a51b304c8",
    name: "Cream",
    description: "One Degree",
    mater: [
      {
        mtNumber: 1000,
        id: "64afa9dcda7e337a51b30467",
      },
      {
        mtNumber: 150,
        id: "64afaa08da7e337a51b3046d",
      },
      {
        mtNumber: 250,
        id: "64afa9a4da7e337a51b3045e",
      },
    ],
  },
];

字符串
第二集合结构如下:

materials = [
  {
    _id: "64afaa08da7e337a51b3046d",
    name: "Un",
    type: "Gıda",
    amount: 1000,
    price: 13.5,
    description: "21",
    date: "2023-07-05T00:00:00.000Z",
  },
  {
    _id: "64afa9a4da7e337a51b3045e",
    name: "Toz Şeker",
    type: "Gıda",
    amount: 1000,
    price: 22,

    date: "2023-07-13T00:00:00.000Z",
  },
  {
    _id: "64afa9dcda7e337a51b30467",
    name: "Tereyağ",
    type: "Gıda",
    amount: 1000,
    price: 170,
    date: "2023-07-13T00:00:00.000Z",
  },
];


主数组第一个集合中的“id”和第二个集合中的“_id”相关。
我需要下面的结构,需要在第一个集合总列,并从第二个集合值

semiproducts = [
  {
    _id: "64afad9eda7e337a51b304c8",
    name: "Cream",
    description: "One Degree",
    mater: [
      {
        mtNumber: 1000,
        id: "64afa9dcda7e337a51b30467",
      },
      {
        mtNumber: 150,
        id: "64afaa08da7e337a51b3046d",
      },
      {
        mtNumber: 250,
        id: "64afa9a4da7e337a51b3045e",
      },
    ],
> totalPrice: 1253 //sum of second collection material prices
  },
];


我尝试了聚合查询与下面的结构,但它没有工作,因为我想要的。

[
  {
    $lookup: {
      from: "materials",
      let: { mat_id: "$mater.id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: ["$_id", "$$mat_id"],
            },
          },
        },
      ],
      as: "mat_info",
    },
  },
  {
    $addFields: {
      total: { $sum: "$mat_info.price" },
    },
  },
];


从现在开始谢谢你

oknrviil

oknrviil1#

试试看

db.semiproducts.aggregate([
  {
    $lookup: {
      from: "materials",
      localField: "mater.id",
      foreignField: "_id",
      as: "mat"
    }
  },
  {
    $addFields: {
      totalPrice: {
        $sum: "$mat.price"
      }
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      description: 1,
      mater: 1,
      totalPrice: 1
    }
  }
])

字符串
https://mongoplayground.net/p/5H0D_PUdxXn

总价格:1253 //第二次收集材料价格之和

我认为你的期望值是错误的。170+22+13.5 = 205.5

相关问题