mongodb聚合与$ match和unwind

时间:2016-09-29 08:59:12

标签: arrays mongodb

基于this问题......

我正在尝试创建一个聚合函数,并根据子数组中的值过滤我的数组。目前我的数组结构如下:

'id':1,
'data': {
   'value':1    
 }
'id':2,
'data': {
   'value':1    
 }
'id':3,
'data': {
   'value':2    
 }

所以我需要获取data.value为1的所有项目。目前为了做到这一点,我必须执行以下操作:

db.ids.aggregate([
{$match:{id:{$exists:true}}}, //some more matching conditions here...
{$unwind:'$data'},
{$match:{'data.value':1}}//need to get rid of this and move it to the first $match

所以问题是我可以摆脱第二场$ match并将我的子阵列过滤条件放入第一场比赛吗?我试图这样做,但它没有工作,并返回整个文件。我真的需要根据子阵列值过滤我的数组,因为我的数据库会变得非常大,我不想在整堆文件中放松。 谢谢。

2 个答案:

答案 0 :(得分:0)

您可以在第一场比赛中添加多个条件。

db.ids.aggregate([
  {$match:{id:{$exists:true}, "data.value": 1}}
])

然后放松一下。

答案 1 :(得分:-1)

尝试以下:

 db.ids.aggregate([
{$match:{id:{$exists:true}}, 'data.value':1},
{$unwind:'$data'}
相关问题