编写一个 MongoDB 查询以获取嵌值?


你可以使用点表示法来获取嵌套值。我们首先创建一个包含文档的集合

> 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"
   }
}

更新日期:2019-07-30

148 次浏览

开启你的职业生涯

完成课程,获得认证

开始吧
广告