我在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" },
},
},
];
型
从现在开始谢谢你
1条答案
按热度按时间oknrviil1#
试试看
字符串
https://mongoplayground.net/p/5H0D_PUdxXn
总价格:1253 //第二次收集材料价格之和
我认为你的期望值是错误的。170+22+13.5 = 205.5