2016-09-21 108 views
1

我想有一个返回一个布尔值,如果一个字段包含在数组中,喜欢的一步:

$project: { 
    // would return whether the field 'type' is banana or apple 
    isFruit: { $type: { $in: ['apple', 'banana'] } }, 
}, 

但是,这是行不通的。看看doc,我看不到包含测试。那可能吗?

回答

1

这有点令人费解,但你可以通过使用$filter来过滤输入数组做到这一点,只是元素匹配type,然后比较反对[]结果(如果有的话):

db.test.aggregate([ 
    {$project: { 
     isFruit: { $ne: [[], { $filter: { 
      input: ['apple', 'banana'], 
      as: 'fruit', 
      cond: { $eq: ['$$fruit', '$type'] } 
     }}]} 
    }} 
]) 

注意在MongoDB 3.2中添加了$filter

+0

这看起来不错!任何关于可能的性能缺点的想法? – Guig

+0

@Guig我不确定它会如何扩展,您必须在真实场景中进行测试。 – JohnnyHK