我有一个这样的文件:
{
"_id": ObjectId("55fa4615b70ad91c40069736"),
"test": [
null,
true
]
}
"test"
字段是包含2个元素的数组。我想计算没有null
值使用聚合的数组的数量。我喜欢这样:
{$project: { count: { $size: '$test' } }}.
但它返回2.我希望它返回1(不计算null
值)
答案 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}})