要从嵌套的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" } ] } }