訪問 MongoDB 中 JSON 陣列的內建元素?


要訪問 MongoDB 中 JSON 陣列中的內部元素,請使用點號表示法。讓我們用文件建立一個集合 -

> db.demo687.insert({CountryName:'US',
... info:
... {
... id:101,
... details:
... [
... {
...    Name:'Chris',
...    SubjectName:'MongoDB',
...    otherDetails:{
...       "Marks":58,
...       Age:23
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo687.insert({CountryName:'UK',
... info:
... {
... id:102,
... details:
... [
... {
...    Name:'David',
...    SubjectName:'MySQL',
...    otherDetails:{
...       "Marks":78,
...       Age:21
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })

使用 find() 方法顯示集合中的所有文件 -

> db.demo687.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }
{ "_id" : ObjectId("5ea55673a7e81adc6a0b3963"), "CountryName" : "UK", "info" : { "id" : 102, "details" : [ { "Name" : "David", "SubjectName" : "MySQL", "otherDetails" : { "Marks" : 78, "Age" : 21 } } ] } }

以下是訪問 JSON 陣列內部元素的查詢 -

> db.demo687.find({"info.details.otherDetails.Marks":58});

這將產生以下輸出 -

{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }

更新於:14-5-2020

605 瀏覽次數

開啟你的 職業生涯

完成課程取得認證

開始
廣告