如何获取 MongoDB 文档中的嵌入式数据?
以下是获取 MongoDB 文档中嵌入式数据所需的语法
db.yourCollectionName.find({},{‘yourOuterKeyName.yourInnerKeyName:1}).pretty();
让我们先创建包含文档的集合
> db.embeddedCollectionDemo.insertOne( ... { ... "StudentName" : "Larry", ... "StudentDetails": { ... "Larry1234": {"ProjectName": "Student Web Tracker"}, ... "Larry7645": {"ProjectName": "Hospital Management System"}, ... "Larry9879": {"ProjectName": "Library Management System"}, ... ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c98a100330fd0aa0d2fe4c5") }
以下是显示集合中所有文档的查询
> db.embeddedCollectionDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"), "StudentName" : "Larry", "StudentDetails" : { "Larry1234" : { "ProjectName" : "Student Web Tracker" }, "Larry7645" : { "ProjectName" : "Hospital Management System" }, "Larry9879" : { "ProjectName" : "Library Management System" } } }
以下是嵌入式集合(即 MongoDB 集合中的嵌入式数据)的查询
> db.embeddedCollectionDemo.find({},{'StudentDetails.Larry7645':1}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c98a100330fd0aa0d2fe4c5"), "StudentDetails" : { "Larry7645" : { "ProjectName" : "Hospital Management System" } } }
广告