gpt4 book ai didi

javascript - 我应该怎么做聚合?

转载 作者:行者123 更新时间:2023-11-30 21:06:08 24 4
gpt4 key购买 nike

我有一个包含产品(对象)的数组。看起来像:

[
{_id: 123, name:'first', category:'Vape', property:[
{key:'brand', values:'Eleaf'},
{key:'mechmode', values:'some'},
{key:'color', values:['red', 'blue']},
{key:'batrtype', values:'some2'},
]},
{_id: 1234, name:'second', category:'Vape1', property:[
{key:'brand', values:'Eleaf1'},
{key:'mechmode', values:'some'},
{key:'color', values:['black']},
{key:'batrtype', values:'some2'}
]},
{_id: 12345, name:'third', category:'Vape3', property:[
{key:'brand', values:'Eleaf3'},
{key:'mechmode', values:'some'},
{key:'color', values:['green', 'yellow']},
{key:'batrtype', values:'some2'}
]},
{_id: 123456, name:'fourth', category:'Vape', property:[
{key:'brand', values:'Eleaf'},
{key:'mechmode', values:'some'},
{key:'color', values:['red', 'green']},
{key:'batrtype', values:'some2'}
]}
]

来自客户的请求

{category:'Vape', body:{brand:'Eleaf', color:'red'}}

我应该如何在 mongo 中进行聚合以获得品牌 = 'Eleaf' 的产品颜色=红色根据要求?

有人可以帮忙吗?

最佳答案

bgraham如果您使用的是 find,则答案完全正确。要在聚合管道中做同样的事情,请使用 $match ,例如:

db.aggregate([{$match:{
category: "Vape",
$and: [
{ property: { $elemMatch: { key: "brand", value: "Eleaf" },
{ property: { $elemMatch: { key: "color", value: "red" }
]
}}])

然后您可以将所需的任何其他流水线阶段添加到数组中。

关于javascript - 我应该怎么做聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573278/

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