MongoDB 创建产品汇总集合

s.f*_*frz 6 mongoose mongodb node.js

假设我有一个这样的产品系列:

{
"_id": "5a74784a8145fa1368905373",
"name": "This is my first product",
"description": "This is the description of my first product",
"category": "34/73/80",
"condition": "New",
"images": [
    {
        "length": 1000,
        "width": 1000,
        "src": "products/images/firstproduct_image1.jpg"
    },
    ...
],

"attributes": [
    {
        "name": "Material",
        "value": "Synthetic"
    },
    ...
],

"variation": {
    "attributes": [
        {
            "name": "Color",
            "values": ["Black", "White"]
        },
        {
            "name": "Size",
            "values": ["S", "M", "L"]
        }
    ]
}
}
Run Code Online (Sandbox Code Playgroud)

和这样的变体集合:

{
"_id": "5a748766f5eef50e10bc98a8",
"name": "color:black,size:s",
"productID": "5a74784a8145fa1368905373",
"condition": "New",
"price": 1000,
"sale": null,
"image": [
    {
        "length": 1000,
        "width": 1000,
        "src": "products/images/firstvariation_image1.jpg"
    }
],
"attributes": [
    {
        "name": "Color",
        "value": "Black"
    },
    {
        "name": "Size",
        "value": "S"
    }
]
}
Run Code Online (Sandbox Code Playgroud)

我想将文档分开,为了便于浏览、搜索和分面搜索实现,我想在单个查询中获取所有数据,但我不想加入我的应用程序代码。我知道使用名为 summary 的第三个集合可以实现,它可能如下所示:

{
"_id": "5a74875fa1368905373",
"name": "This is my first product",
"category": "34/73/80",
"condition": "New",
"price": 1000,
"sale": null,
"description": "This is the description of my first product",
"images": [
    {
        "length": 1000,
        "width": 1000,
        "src": "products/images/firstproduct_image1.jpg"
    },
    ...
],

"attributes": [
    {
        "name": "Material",
        "value": "Synthetic"
    },
    ...
],

"variations": [
    {
        "condition": "New",
        "price": 1000,
        "sale": null,
        "image": [
            {
                "length": 1000,
                "width": 1000,
                "src": "products/images/firstvariation_image.jpg"
            }
        ],
        "attributes": [
            "color=black",
            "size=s"
        ]
    },
    ...
]
}
Run Code Online (Sandbox Code Playgroud)

问题是,我不知道如何使汇总集合与产品和变体集合保持同步。我知道可以使用 mongo-connector 来完成,但我不确定如何实现它。请帮助我,我仍然是一个初学者程序员。

Sar*_*ana 0

您实际上不需要维护摘要集合,将产品和变体摘要存储在另一个集合中是多余的

您可以使用聚合管道$lookup来使用 ProductID 外部连接产品和变体

骨料管道

db.products.aggregate(
    [
        {
            $lookup : {
                from : "variation",
                localField : "_id",
                foreignField : "productID",
                as : "variations"
            }
        }
    ]
).pretty()
Run Code Online (Sandbox Code Playgroud)