仅返回MongoDB文档中的数组字段

1 投票
1 回答
45 浏览
提问于 2025-04-14 17:24

我有一个MongoDB的集合,每个文档的格式如下:

    {
        "course_id": "course_id",
        "language": "language",
        "topics": [
            {
                "topic_id": "topic_id",
                "topic_title": "topic_title",
                "topic_description": "topic_description",
            },
        ],
    }

我想做的是,根据一个course_id和一个language,获取一个数组(只要这个数组,不要包含topics字段的文档),这个数组里的每个元素只包含topic_idtopic_title字段,比如:

[
  {"topic_id": "id_1", "topic_title": "title1"},
  {"topic_id": "id_2", "topic_title": "title2"},
]

为了获取仅仅是这个数组,我使用了.distinct()方法,具体如下:

result = db.topics_collection.distinct("topics", {"course_id": course_id, "language": language})

现在我还需要过滤掉topic_description字段,但我尝试的以下查询没有成功:

result = db.topics_collection.distinct("topics", {{"course_id": course_id, "language": language}, {"topic_description": 0}})

有没有其他方法(也许可以用不同于.distinct()的方法)来过滤掉topic_description字段呢?

1 个回答

1

你可以使用aggregate这个方法来处理这种情况:

result = db.topics_collection.aggregate([
  {
    $match: {
      course_id: course_id,
      language: language
    }
  },
  {
    $unwind: "$topics"
  },
  {
    $replaceRoot: {
      newRoot: "$topics"
    }
  },
  {
    $project: {
      topic_id: 1,
      topic_title: 1
    }
  }
])

想看一个实际的例子,可以点击这里

下面是一些解释:

  1. $match: 这是你查询的条件。
  2. $unwind: 把$topics这个数组拆分成单独的文档。
  3. $replaceRoot: 用每个新文档中的$topics对象替换原来的文档。
  4. $project: 只保留你想要的属性。

撰写回答