要将内嵌文档展开到主文档显示,并对内嵌文档的所有属性都加上 "pets_" 前缀,可以使用 MongoDB 的聚合操作来实现。具体步骤如下:

  1. 使用 $unwind 操作符将 pets 字段展开为多个文档。
  2. 使用 $objectToArray 操作符将内嵌文档的属性转换为数组。
  3. 使用 $project 操作符对数组中的每个元素进行重命名,并加上 "pets_" 前缀。
  4. 使用 $group 操作符将展开后的文档重新聚合为一个文档。

以下是具体的聚合查询示例代码:

db.collection.aggregate([
  { $unwind: "$pets" },
  { $project: { _id: 1, name: 1, age: 1, pets: { $objectToArray: "$pets" } } },
  { $unwind: "$pets" },
  { $project: { _id: 1, name: 1, age: 1, ["pets_" + $pets.k]: $pets.v } },
  { $group: { _id: "$_id", name: { $first: "$name" }, age: { $first: "$age" }, pets: { $push: { name: "$pets_name", type: "$pets_type" } } } }
])

运行以上聚合查询后,会得到以下结果:

{
  "_id": 1,
  "name": "John",
  "age": 30,
  "pets_name": "Fluffy",
  "pets_type": "cat"
}

注意:以上示例中的 "collection" 需要替换为实际的集合名称。

MongoDB 聚合查询:将内嵌文档展开到主文档并添加前缀 - $objectToArray 实现

原文地址: https://www.cveoy.top/t/topic/qax7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录