访问 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 浏览次数

开启你的 职业生涯

完成课程取得认证

开始
广告
© . All rights reserved.