从 MongoDB 中的嵌套对象结构中访问对象
使用点表示法访问对象。首先,让我们创建一个包含文档的集合
> db.nestedObjectDemo.insertOne({"Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], ... "StudentCountryName" : [ "US" ], ... "StudentCoreSubject" : [ "C", "Java" ], ... "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }); { "acknowledged" : true, "insertedId" : ObjectId("5c99dfc2863d6ffd454bb650") }
以下查询会使用 find() 方法显示集合中的所有文档
> db.nestedObjectDemo.find().pretty();
这会生成以下输出
{ "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }
以下查询会使用点表示法访问嵌套对象
>db.nestedObjectDemo.find({"Student.StudentDetails.StudentPersonalDetails.StudentName":"John"}).pretty();
这会生成以下输出
{ "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }
广告