Consider a collection called pet_owners where every document contains the following fields: { "_id": 334244122, "name": "Bob", "pets": [ "dog", "cat", "alligator" ] } The Aggregation below is intended to determine the average number of pets owned by pet owners in this collection. db.col.aggregate([ { "$unwind": "$pets" }, { "$group": { "_id": "$_id", "n_pets": { "$sum": 1 } } }, { "$project": { "_id": 1 , "average_pets": { "$avg": "$n_pets" } } } ]) Which of the following Aggregation Stages should be used to replace "AGGREGATION_STAGE"? Choose the best answer:
题目选项
- A.$project
- B.$match
- C.$group
- D.$sort
答案置信度:高
正确答案:C
解析语言:中文
原答案 A($project)不成立:题目要的是所有养宠人平均拥有的宠物数,必须把全部文档收进同一个分组再求 $avg,所以第三个阶段必须是 $group(_id 用常量 1 表示所有文档同组)。$project 里的 $avg 只对当前文档的数组或标量求平均,而这里的 $n_pets 是标量,用它只会原样返回每个人的宠物数,得不到全集合平均值。源卷中保留了 AGGREGATION_STAGE 占位符的版本(1-DEV / 李和平卷)记录的答案就是 $group,可相互印证。