我有一个MongoDB集合,其中每个文档都具有以下格式:

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

我要做的是在给定course_idlanguage的情况下检索一个数组(and only the array, not a document with the 102 field),其中每个元素只有topic_idtopic_title字段,例如:

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

为了检索only the array,我使用.distinct()方法,如下所示:

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

现在,我还需要过滤掉topic_description字段,但我try 的以下查询不起作用:

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
    }
  }
])

有关工作示例,请参见HERE.

解释:

  1. $match:您的查询条件.
  2. $unwind:将$topics数组放入单独的文档中.
  3. $replaceRoot:包含来自每个新文档的$topics对象的文档.
  4. $project:仅限您想要的属性.

Python相关问答推荐

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

如何避免Chained when/then分配中的Mypy不兼容类型警告?

如何制作10,000年及以后的日期时间对象?

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

如何在Python中并行化以下搜索?

UNIQUE约束失败:customuser. username

如何从列表框中 Select 而不出错?

启动带有参数的Python NTFS会导致文件路径混乱

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

如何在达到end_time时自动将状态字段从1更改为0

* 动态地 * 修饰Python中的递归函数

在单次扫描中创建列表

网格基于1.Y轴与2.x轴显示在matplotlib中

幂集,其中每个元素可以是正或负""""

如何使用正则表达式修改toml文件中指定字段中的参数值

以异步方式填充Pandas 数据帧

Pandas:根据相邻行之间的差异过滤数据帧

如何在微调Whisper模型时更改数据集?

使用Django标签显示信息