要动态遍历处理内嵌文档,可以使用MongoDB的聚合操作中的$unwind和$group操作符。\n\n首先,使用$unwind操作符将pets数组展开为多个文档,每个文档都包含一个宠物。\n\n然后,使用$group操作符将展开后的文档重新组合成一个文档,并将内嵌文档的字段展开到主文档中。\n\n以下是一个示例聚合查询的代码:\n\njavascript\ndb.collection.aggregate([\n {\n $unwind: "$pets" // 将pets数组展开为多个文档\n },\n {\n $group: {\n _id: "$_id", // 根据主文档的_id字段进行分组\n name: { $first: "$name" }, // 保留主文档的name和age字段\n age: { $first: "$age" },\n pets_name: { $push: "$pets.name" }, // 将pets数组中的name字段存入pets_name数组\n pets_type: { $push: "$pets.type" } // 将pets数组中的type字段存入pets_type数组\n }\n }\n])\n\n\n执行以上聚合查询后,将得到如下结果:\n\njson\n{\n "_id": 1,\n "name": "John",\n "age": 30,\n "pets_name": ["Fluffy", "Buddy"],\n "pets_type": ["cat", "dog"]\n}\n\n\n注意,pets_name和pets_type字段的值是数组,因为pets数组中可能有多个宠物。如果只有一个宠物,可以通过使用$first操作符获取第一个元素,将其转为单个值。例如:pets_name: { $first: "$pets.name" }。


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

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