gpt4 book ai didi

node.js - MongoDB 创建产品摘要集合

转载 作者:可可西里 更新时间:2023-11-01 09:16:16 26 4
gpt4 key购买 nike

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

{
"_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 来完成,但我不确定如何实现它。请帮助我,我还是一个初学者。

最佳答案

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

您可以使用聚合管道 $lookup 而不是使用 productID 外部连接产品和变体

聚合管道

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

关于node.js - MongoDB 创建产品摘要集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com