计算mongoDB中没有null的数组

时间:2015-09-21 03:05:27

标签: arrays mongodb

我有一个这样的文件:

{
    "_id": ObjectId("55fa4615b70ad91c40069736"),
    "test": [
        null,
        true
    ]
}

"test"字段是包含2个元素的数组。我想计算没有null值使用聚合的数组的数量。我喜欢这样:

{$project: { count: { $size: '$test' } }}.

但它返回2.我希望它返回1(不计算null值)

2 个答案:

答案 0 :(得分:0)

使用 setIntersection 过滤掉项目中的null以查找数组大小。请检查以下查询:

db.collection.aggregate({"$project":{"testSize":{"$size":{"$setIntersection":["$test",[null]]}}}})

新编辑:

使用aggregation,如下所示:

db.collection.aggregate({
  "$unwind": "$test"
}, {
  "$match": {
    "test": {
      "$ne": null
    }
  }
}, {
  "$group": {
    "_id": "$_id",
    "test": {
      "$push": "$test"
    }
  }
}, {
  "$project": {
    "testSize": {
      "$size": "$test"
    }
  }
})

答案 1 :(得分:0)

试试这个

    db.collection.aggregate({"$unwind": "$test"
}, {
  "$match": {
    "test": {
      "$ne": null
    }
  }
},
 {$group:
{_id:"size",
  size:{$sum:1}}},
{$project:{_id:0,size:1}})