從 MongoDB 的巢狀陣列中提取特定元素
使用點(.)表示法從巢狀陣列中提取特定元素。我們首先使用文件建立集合 −
> db.extractParticularElementDemo.insertOne( ... { ... "_id" : 101, ... "StudentName" : "John", ... "StudentInformation" : [ ... { ... "Age" : 21, ... "StudentPersonalInformation" : [ ... { ... "StudentNickName" : "Mike", ... "StudentFamilyDetails" : [ ... { ... "FatherName" : "Carol" ... } ... ] ... }, ... { ... "StudentAnotherName" : "David", ... "StudentFamilyDetails" : [ ... { ... "FatherName" : "Robert" ... } ... ] ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
以下是使用 find() 方法從集合中顯示所有文件的查詢 −
> db.extractParticularElementDemo.find().pretty();
這將產生以下輸出 −
{ "_id" : 101, "StudentName" : "John", "StudentInformation" : [ { "Age" : 21, "StudentPersonalInformation" : [ { "StudentNickName" : "Mike", "StudentFamilyDetails" : [ { "FatherName" : "Carol" } ] }, { "StudentAnotherName" : "David", "StudentFamilyDetails" : [ { "FatherName" : "Robert" } ] } ] } ] }
以下是用於從巢狀陣列中提取特定元素的查詢 −
> db.extractParticularElementDemo.find( ... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'}, ... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0} ... ).pretty();
這將產生以下輸出 −
{ "StudentInformation" : [ { "StudentPersonalInformation" : [ { "StudentFamilyDetails" : [ { } "FatherName" : "Carol" ] }, { "StudentFamilyDetails" : [ { "FatherName" : "Robert" } ] } ] } ] }
廣告