您可以使用点表示法来获取嵌套值。首先让我们创建一个包含文档的集合
> db.nestedQueryDemo.insertOne( ... { ... ... "EmployeeName" : "John", ... "EmployeeDetails" : ... { ... ... "_id":"EMP-101", ... "EmployeeAge":23, ... "EmployeeCompanyName":"IBM" ... ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c9ea31dd628fa4220163b69") } > db.nestedQueryDemo.insertOne( ... { ... ... "EmployeeName" : "Carol", ... "EmployeeDetails" : ... { ... ... "_id":"EMP-110", ... "EmployeeAge":29, ... "EmployeeCompanyName":"Amazon" ... ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c9ea36bd628fa4220163b6a") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.nestedQueryDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ea31dd628fa4220163b69"), "EmployeeName" : "John", "EmployeeDetails" : { "_id" : "EMP-101", "EmployeeAge" : 23, "EmployeeCompanyName" : "IBM" } } { "_id" : ObjectId("5c9ea36bd628fa4220163b6a"), "EmployeeName" : "Carol", "EmployeeDetails" : { "_id" : "EMP-110", "EmployeeAge" : 29, "EmployeeCompanyName" : "Amazon" } }
以下是对MongoDB嵌套值查询的查询
> db.nestedQueryDemo.find({"EmployeeDetails._id":"EMP-110"}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ea36bd628fa4220163b6a"), "EmployeeName" : "Carol", "EmployeeDetails" : { "_id" : "EMP-110", "EmployeeAge" : 29, "EmployeeCompanyName" : "Amazon" } }