MongoDB能否基于自定义Person Schema识别异构文档中的人员?
MongoDB相关问题解答
1. 能否插入结构、嵌套层级各异的文档?
完全可以。MongoDB是无模式数据库,同集合中的文档不需要遵循统一结构,支持插入字段数量、嵌套层级完全不同的文档——这也是它和你熟悉的GraphQL/dgraph强Schema模式的核心差异之一。
2. 能否通过定义Person Schema找出两个文档中的“人员”?
MongoDB的Schema(无论是原生Schema Validation还是Mongoose这类ODM工具的Schema)主要作用是约束插入/更新的文档结构,无法直接通过Schema跨层级提取数据,但可以通过查询语句实现需求:
提取顶层结构的人员(第一个文档)
用find查询匹配包含first_name、last_name、dob的文档,并投影指定字段:
db.yourCollection.find( { first_name: { $exists: true }, last_name: { $exists: true }, dob: { $exists: true } }, { first_name: 1, last_name: 1, dob: 1, _id: 0 } )
提取嵌套结构的人员(第二个文档中的partner)
通过聚合的$project提取嵌套字段:
db.yourCollection.aggregate([ { $match: { partner: { $exists: true } } }, { $project: { first_name: "$partner.first_name", last_name: "$partner.last_name", dob: "$partner.dob", _id: 0 } } ])
统一提取两种结构的人员数据
用聚合的$facet和$concatArrays整合结果:
db.yourCollection.aggregate([ { $facet: { topLevelPersons: [ { $match: { first_name: { $exists: true }, last_name: { $exists: true }, dob: { $exists: true }, partner: { $exists: false } } }, { $project: { first_name: 1, last_name: 1, dob: 1, _id: 0 } } ], nestedPersons: [ { $match: { partner: { $exists: true } } }, { $project: { first_name: "$partner.first_name", last_name: "$partner.last_name", dob: "$partner.dob", _id: 0 } } ] } }, { $project: { allPersons: { $concatArrays: ["$topLevelPersons", "$nestedPersons"] } } }, { $unwind: "$allPersons" }, { $replaceRoot: { newRoot: "$allPersons" } } ])
如果需要规范Person结构的插入验证,可以定义Schema Validation或使用Mongoose Schema,但这仅用于约束文档结构,查询仍需依赖上述语句。
内容的提问来源于stack exchange,提问作者JohnDoe
相关产品推荐
相关产品推荐

