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

问题描述 投票:0回答:1

我有一个 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_id 
topic_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
字段?

python mongodb pymongo
1个回答
0
投票

您可以使用 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
    :只有您想要的属性。
© www.soinside.com 2019 - 2024. All rights reserved.