我有一个 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
字段?
您可以使用 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
}
}
])
请参阅此处了解工作示例。
说明:
$match
:您的查询条件。$unwind
:将 $topics
数组放入单独的文档中。$replaceRoot
:包含每个新文档中的 $topics
对象的文档。$project
:只有您想要的属性。