2016-09-02 55 views
3

例如,我有收集与以下类型:由字段值返回阵列的第一匹配

[ 
    { batch: false, type: '' }, 
    { batch: false, type: '' }, 
    { batch: true, type: '123' }, 
    { batch: true, type: '123' }, 
    { batch: true, type: '123' }, 
    { batch: true, type: '234' }, 
    { batch: true, type: '234' }, 
    { batch: true, type: '234' }, 
    { batch: true, type: '234' }, 
    { batch: true, type: '567' }, 
    { batch: true, type: '567' } 
] 

所以问题是,如何以返回其具有{batch: false}并且如果{batch: true}返回仅与同一{type}第一对象的对象的阵列场,基本上我希望得到如下回应:

[ 
    { batch: false, type: '' }, 
    { batch: false, type: '' }, 
    { batch: true, type: '123' }, 
    { batch: true, type: '234' }, 
    { batch: true, type: '567' } 
] 
+1

我的文档编辑出来的'_id'场,因为我认为这是多余的在这里。 – styvane

回答

2

尝试以下聚合管道

db.getCollection('yourCollection').aggregate([ 
    { 
     $group: { 
      _id: { 
       k1: { 
        $cond: { 
         if: "$batch", 
         then: null, 
         else: "$_id" 
        } 
       }, 
       k2: "$type" 
      }, 
      batch: { $first: "$batch" }, 
      type: { $first: "$type" } 
     } 
    }, 
    { 
     $project: { 
      _id: 0, 
      batch: 1, 
      type: 1 
     } 
    } 
]) 

导致

/* 1 */ 
{ 
    "batch" : false, 
    "type" : "" 
} 

/* 2 */ 
{ 
    "batch" : false, 
    "type" : "" 
} 

/* 3 */ 
{ 
    "batch" : true, 
    "type" : "123" 
} 

/* 4 */ 
{ 
    "batch" : true, 
    "type" : "567" 
} 

/* 5 */ 
{ 
    "batch" : true, 
    "type" : "234" 
} 
2

运行以下聚集管线中,你需要有一个条件中满足给定条件的$group键:

db.collection.aggregate([ 
    { 
     "$group": { 
      "_id": { "$cond": [ "$batch", "$type", "$_id" ] }, 
      "batch": { "$first": "$batch" }, 
      "type": { "$first": "$type" } 
     } 
    }, 
    { "$project": { "_id": 0, "batch": 1, "type": 1 } } 
]) 
+2

好的答案,但(理论上)当'type'和'_id'来自同一个域时碰撞的可能风险 – DAXaholic