MongoDB 创建产品摘要集合。

6

假设我有这样一个产品集合:

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

我希望将文档分开存储,为了方便浏览、搜索和使用faceted搜索,我想在单个查询中获取所有数据,但是我不想在我的应用程序代码中进行连接操作。 我知道可以通过创建第三个名为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

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

相反,您可以使用聚合管道$lookup来使用productID外连接产品和变体

聚合管道

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

1
谢谢,你的回答有所帮助...但如果我想像这里提到的那样仍然维护摘要集合怎么办?https://dzone.com/articles/product-catalog-part-1-schema。 - s.frz
@s.frz,老兄,你有没有找到任何方法来使摘要文档与其他集合同步?我期待着你的帮助。 - Firoj Siddiki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接