从 MongoDB 中的嵌套 JSON 数组中检索值?
要从嵌套的 JSON 数组中检索值,可以使用以下语法 −
db.yourCollectionName.find({"yourOuterFieldName.yourInnerFieldName.yourNextInnerFieldName…...N": "yourValue"}).pretty();
我们先创建一个包含文档的集合 −
> db.nestedJSONArrayDemo.insertOne({ ... "ClientDetails" : ... { ... "ClientPersonalDetails" : [ ... { "CountryName" : "US" }, ... { "CountryName" : "AUS"}, ... { "ClientName":"Chris" }, ... { "ClientName":"David" } ... ] ... } ... }); { "acknowledged" : true, "insertedId" : ObjectId("5cd2cbb2b64f4b851c3a13bc") } > db.nestedJSONArrayDemo.insertOne({ ... "ClientDetails" : ... { ... "ClientPersonalDetails" : [ ... { "CountryName" : "Belgium" }, ... { "CountryName" : "Canada"}, ... { "CountryName" : "Egypt"}, ... ] ... } ... }); { "acknowledged" : true, "insertedId" : ObjectId("5cd2cc14b64f4b851c3a13bd") }
以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.nestedJSONArrayDemo.find().pretty();
这将生成以下输出 −
{ "_id" : ObjectId("5cd2cbb2b64f4b851c3a13bc"), "ClientDetails" : { "ClientPersonalDetails" : [ { "CountryName" : "US" }, { "CountryName" : "AUS" }, { "ClientName" : "Chris" }, { "ClientName" : "David" } ] } } { "_id" : ObjectId("5cd2cc14b64f4b851c3a13bd"), "ClientDetails" : { "ClientPersonalDetails" : [ { "CountryName" : "Belgium" }, { "CountryName" : "Canada" }, { "CountryName" : "Egypt" } ] } }
以下是从 MongoDB 中的嵌套 JSON 数组中检索值的查询 −
> db.nestedJSONArrayDemo.find({"ClientDetails.ClientPersonalDetails.CountryName": "Canada"}).pretty();
这将生成以下输出 −
{ "_id" : ObjectId("5cd2cc14b64f4b851c3a13bd"), "ClientDetails" : { "ClientPersonalDetails" : [ { "CountryName" : "Belgium" }, { "CountryName" : "Canada" }, { "CountryName" : "Egypt" } ] } }
广告