mongodb Mongoose -过滤多个文档中的子文档并获取为普通数组

j2cgzkjk  于 2023-02-18  发布在  Go
关注(0)|答案(1)|浏览(157)

我有一个电子商务应用程序,其中的产品有多个变体,因此,变体存储在每个Product对象的数组中。

[
    {
      title: "Test"
      description: "test description",
      ....
      ....
      variants: [
        {
           color: "red",
           size: "L"
           ....
           ....
           price: 500
        },
        {
           color: "red",
           size: "M"
           ....
           ....
           price: 500
        },
        {
           color: "red",
           size: "S"
           ....
           ....
           price: 500
        },    
      ]
    }
]

有没有一种方法可以通过ID过滤这些产品变体,并作为变体的普通数组返回,忽略它们来自不同的父代,但使用父代详细信息?

[
        {
           color: "red",
           size: "L"
           ....
           ....
           price: 500,
           parent: {
             title: "Test"
             description: "test description"
           }
        },
        {
           color: "red",
           size: "M"
           ....
           ....
           price: 500,
           parent: {
             title: "Test"
             description: "test description"
           }
        },
        {
           color: "red",
           size: "S"
           ....
           ....
           price: 500,
           parent: {
             title: "Test"
             description: "test description"
           }
        },
        {
           color: "orange",
           size: "S"
           ....
           ....
           price: 500,
           parent: {
             title: "Test 2"
             description: "test description 2"
           }
        },  
]
0kjbasz6

0kjbasz61#

查询1

  • 添加一个名为parent的字段,其中包含根目录中的字段(variants除外)
  • 删除这些字段,保留variants
  • 用于在数组variants中添加parent字段的Map
  • 展开variants并替换根

Playmongo

aggregate(
[{"$set": {"parent": {"title": "$title", "description": "$description"}}},
 {"$unset": ["title", "description"]},
 {"$set": 
   {"variants": 
     {"$map": 
       {"input": "$variants",
        "in": {"$mergeObjects": ["$$this", {"parent": "$parent"}]}}}}},
 {"$unwind": "$variants"},
 {"$replaceRoot": {"newRoot": "$variants"}}])

查询2

  • 与上述相同,只是阶段较少,1组进行前3个阶段

Playmongo

aggregate(
[{"$set": 
   {"title": "$$REMOVE",
    "description": "$$REMOVE",
    "variants": 
     {"$map": 
       {"input": "$variants",
        "in": 
         {"$mergeObjects": 
           ["$$this",
             {"parent": 
               {"title": "$title", "description": "$description"}}]}}}}},
 {"$unwind": "$variants"}, {"$replaceRoot": {"newRoot": "$variants"}}])

相关问题