从子数组中查找 MongoDB 文档?
你可以使用点(.)符号从子数组中查找文档。让我们首先创建一个包含文档的集合 −
> db.findDocumentDemo.insertOne( ... { ... "EmployeeDetails" : ... { ... "EmployeeAppraisalTime": ... ... [ ... ... {"EmployeeDesignation": "Developer", "Salary": 45000}, ... {"EmployeeDesignation": "Tester", "Salary": 30000}, ... {"EmployeeDesignation": "HR", "Salary": 22000}, ... {"EmployeeDesignation": "Accountant", "Salary": 18000} ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2c0f7b64f4b851c3a13a8") } > db.findDocumentDemo.insertOne( ... { ... "EmployeeDetails" : ... { ... "EmployeeAppraisalTime": ... ... [ ... ... {"EmployeeDesignation": "Developer", "Salary": 105000}, ... {"EmployeeDesignation": "Tester", "Salary": 45000}, ... {"EmployeeDesignation": "HR", "Salary": 34000}, ... {"EmployeeDesignation": "Accountant", "Salary": 24000} ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2c1d5b64f4b851c3a13a9") }
以下查询使用 find() 方法从集合中显示所有文档 −
> db.findDocumentDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd2c0f7b64f4b851c3a13a8"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 45000 }, { "EmployeeDesignation" : "Tester", "Salary" : 30000 }, { "EmployeeDesignation" : "HR", "Salary" : 22000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 18000 } ] } } { "_id" : ObjectId("5cd2c1d5b64f4b851c3a13a9"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 105000 }, { "EmployeeDesignation" : "Tester", "Salary" : 45000 }, { "EmployeeDesignation" : "HR", "Salary" : 34000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 24000 } ] } }
以下查询从子数组中查找文档 −
> db.findDocumentDemo.find({ 'EmployeeDetails.EmployeeAppraisalTime.EmployeeDesignation': 'Developer', 'EmployeeDetails.EmployeeAppraisalTime.Salary': { '$in': [45000,105000] } } );
这将产生以下输出 −
{ "_id" : ObjectId("5cd2c0f7b64f4b851c3a13a8"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 45000 }, { "EmployeeDesignation" : "Tester", "Salary" : 30000 }, { "EmployeeDesignation" : "HR", "Salary" : 22000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 18000 } ] } } { "_id" : ObjectId("5cd2c1d5b64f4b851c3a13a9"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 105000 }, { "EmployeeDesignation" : "Tester", "Salary" : 45000 }, { "EmployeeDesignation" : "HR", "Salary" : 34000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 24000 } ] } }
广告