MongoDB DEV · Question 191 · Single choice

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:

Answer options

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

Answer confidence: High

Correct answer: C

Explanation language: Chinese

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

Papers containing this question

This question appears in 3 bank records. Public pages combine identical prompts and options. Selected questions display the highest-confidence record; the others show a short preview. Paper-based learning preserves each record's answer, explanation, and confidence.

AUTHOR · PROJECTS · OPEN SOURCE

Author & MongoDB projects

Building data platforms, MongoDB migration and sync tools, and cloud operations products.

Contact the author for any MongoDB needs.

Contact the author ↗mlhp123@outlook.com

Support the author

If this question bank helps you, optional donations are welcome.

Scan with Alipay to support the authorOpen full-size donation image ↗