MongoDB创建产品摘要集合

时间:2018-02-03 20:53:06

标签: node.js mongodb mongoose

说我有这样的产品系列:

{
"_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"]
        }
    ]
}
}

和这样的变体集合:

{
"_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"
    }
]
}

我希望将文档分开,为了便于浏览,搜索和分层搜索实现,我想在单个查询中获取所有数据,但我不想加入我的应用程序代码。 我知道使用名为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"
        ]
    },
    ...
]
}

问题是,我不知道如何使摘要集合与产品和变体集合保持同步。我知道它可以使用mongo-connector完成,但我不知道如何实现它。 请帮助我,我还是一名初学程序员。

1 个答案:

答案 0 :(得分:0)

您实际上并不需要维护摘要集合,它可以在另一个集合中存储产品和变体摘要的冗余

而不是您可以使用产品ID将聚合管道 $ lookup 用于外部联接产品和变体

聚合管道

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