首页 > 解决方案 > 为什么在字段上使用聚合函数 $avg 时 MongoDB 返回 null

问题描述

我不知道为什么这个查询只返回空值,字段中有整数,有些有空值但大多数有整数。我认为 $avg 忽略了空值。这是查询:

db.Companies.aggregate([
    {$group:{_id:”$founded_year”,“avgNumEmployees”:{$avg:“$number_of_employees”}}},
    {$redact:{$cond:{if:{
        $eq:[“$avgNumEmployees”,“null”]},
        then: “$$PRUNE”,
        else:”$$KEEP”}
}}).pretty()

这是来自文档的一些示例数据

_id: 52cdef7c4bab8bd675297d8a
name:"Wetpaint"
permalink:"abc2"
crunchbase_url:
"http://www.crunchbase.com/company/wetpaint"
homepage_url: "http://wetpaint-inc.com"
blog_url:
"http://digitalquarters.net/"
blog_feed_url:
"http://digitalquarters.net/feed/"
twitter_username:"BachelrWetpaint"
category_code:"web"
number_of_employees:47
founded_year:2005
founded_month:10
founded_day:17
deadpooled_year:1
tag_list:
"wiki, seattle, elowitz, media-industry, media-platform, social-distrib..."

这是一个founded_year为null的:

_id:52cdef7c4bab8bd675297d92
name:"Flektor"
permalink:"flektor"
crunchbase_url:
"http://www.crunchbase.com/company/flektor"
homepage_url:
"http://www.flektor.com"
blog_url:
"http://www.flektor-blog.com"
blog_feed_url:
"http://www.flektor-blog.com/video_editing_software/index.rdf"
twitter_username:
null
category_code:
"games_video"
number_of_employees:null
founded_year:null
founded_month:null
founded_day:null
deadpooled_year: null
deadpooled_month: null
deadpooled_day: null
deadpooled_url: null

这些数据来自 mongoDB 的样本训练数据集,称为公司。

标签: mongodb

解决方案


推荐阅读