MongoDB DEV · 题目 191 · 单选

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:

题目选项

  1. A.
    $project
  2. B.
    $match
  3. C.
    $group
  4. D.
    $sort

答案置信度:高

正确答案:C

解析语言:中文

原答案 A($project)不成立:题目要的是所有养宠人平均拥有的宠物数,必须把全部文档收进同一个分组再求 $avg,所以第三个阶段必须是 $group(_id 用常量 1 表示所有文档同组)。$project 里的 $avg 只对当前文档的数组或标量求平均,而这里的 $n_pets 是标量,用它只会原样返回每个人的宠物数,得不到全集合平均值。源卷中保留了 AGGREGATION_STAGE 占位符的版本(1-DEV / 李和平卷)记录的答案就是 $group,可相互印证。

所在套题

此题在题库中有 3 条记录。公开详情合并相同题干和选项;完整公开题展示置信度最高的一条记录,其他题目仅展示摘要。按套学习保留每条记录原有的答案、解析和置信度。

作者 · 作品 · 开源

作者与 MongoDB 作品

专注数据平台、MongoDB 迁移同步与云运维产品研发。

有任何 MongoDB 需求,均可联系作者。

联系作者 ↗mlhp123@outlook.com

支持作者

如果题库对您有帮助,欢迎自愿扫码打赏。

支付宝扫码打赏作者打开打赏原图 ↗