我有一个数组,里面有产品(对象)。看起来像:

[
 {_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'的产品
和颜色=红色根据要求?

有人可以帮忙吗?

最佳答案

如果您使用的是find,则bgraham的答案完全正确。要在聚合管道中执行相同的操作,请使用$match,例如:

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


然后,您可以将所需的任何其他管道阶段添加到阵列。

08-07 09:32