首先让我们创建一个包含文档的集合-
>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeEmail":"Chris12@gmail.com"},{"EmployeeName":"Bob","EmployeeEmail":"bo22@gmail.com"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32f1d8fdf09dd6d08539b9") } >db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"David","EmployeeEmail":"david@gmail.com"},{"EmployeeName":"Carol","EmployeeEmail":"Carol@gmail.com"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32f1f5fdf09dd6d08539ba") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo144.find();
这将产生以下输出-
{ "_id" : ObjectId("5e32f1d8fdf09dd6d08539b9"), "EmployeeDetails" : [ { "EmployeeName" : "Chris", "EmployeeEmail" : "Chris12@gmail.com" }, { "EmployeeName" : "Bob", "EmployeeEmail" : "bo22@gmail.com" } ] } { "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeEmail" : "david@gmail.com" }, { "EmployeeName" : "Carol", "EmployeeEmail" : "Carol@gmail.com" } ] }
以下是在对象数组中查找结果并匹配电子邮件地址字段的查询-
>db.demo144.find({"EmployeeDetails.EmployeeName":"David","EmployeeDetails.EmployeeEmail":"david@gmail.com"},{"EmployeeDetails.EmployeeName":1});
这将产生以下输出-
{ "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David" }, { "EmployeeName" : "Carol" } ] }