MongoDB Creates a Consolidated Product Collection

Let's say I have such a collection of products:

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

and a set of options, for example:

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

I want the documents to be separate and for the convenience of viewing, searching and facsimizing the search, I would like to get all the data in one request, but I do not want to join my application code. I know this is possible with a third collection called summary, which might look like this:

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

is that I don’t know how to keep the composite collection in sync with the collection of products and variations. I know that this can be done using the mongo connector, but I'm not sure how to implement it. help me, I'm still a beginner programmer.

+4
source share
1 answer

,

, $lookup productID

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

Source: https://habr.com/ru/post/1693122/


All Articles