在 MongoDB 中查找对象数组中的结果并匹配电子邮件地址字段?
我们先使用文档创建一个集合 −
>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeEmail":"[email protected]"},{"EmployeeName":"Bob","EmployeeEmail":"[email protected]"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32f1d8fdf09dd6d08539b9") } >db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"David","EmployeeEmail":"[email protected]"},{"EmployeeName":"Carol","EmployeeEmail":"[email protected]"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32f1f5fdf09dd6d08539ba") }
借助 find() 方法显示集合中的所有文档 −
> db.demo144.find();
这将生成以下输出 −
{ "_id" : ObjectId("5e32f1d8fdf09dd6d08539b9"), "EmployeeDetails" : [ { "EmployeeName" : "Chris", "EmployeeEmail" : "[email protected]" }, { "EmployeeName" : "Bob", "EmployeeEmail" : "[email protected]" } ] } { "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeEmail" : "[email protected]" }, { "EmployeeName" : "Carol", "EmployeeEmail" : "[email protected]" } ] }
以下是查找对象数组中的结果并匹配电子邮件地址字段的查询 −
>db.demo144.find({"EmployeeDetails.EmployeeName":"David","EmployeeDetails.EmployeeEmail":"[email protected]"},{"EmployeeDetails.EmployeeName":1});
这将生成以下输出 −
{ "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David" }, { "EmployeeName" : "Carol" } ] }
广告