查询MongoDB嵌套文档中的多个字段

时间:2015-12-30 18:31:48

标签: mongodb mongodb-query

我正在使用MongoDB 3.0.5。我有一个像

这样的集合
db.getCollection('mytest').insert([
{_id: 1, "records": [{"Name": "Joe", "Salary": 70000, "Department": "IT"}]},
{_id: 2, "records": [{"Name": "Henry", "Salary": 80000, "Department": "Sales"}, {"Name": "Jake", "Salary": 40000, "Department": "Sales"}]},
{_id: 3, "records": [{"Name": "Sam", "Salary": 90000, "Department": "IT"}, {"Name": "Tom", "Salary": 50000, "Department": "Sales"}]},
{_id: 4, "records":[{"Name":  "Janice", "Salary": 80000, "Department": "Finance"}, {"Name": "Kale", "Salary": 95000, "Department": "IT"}]}
])

现在我可以查询单个字段,比如IT部门的人员 -

> db.getCollection('mytest').find({"records.Department": {"$in": ["IT"]}}, {"records.$": 1})
{ "_id" : 1, "records" : [ { "Name" : "Joe", "Salary" : 70000, "Department" : "IT" } ] }
{ "_id" : 3, "records" : [ { "Name" : "Sam", "Salary" : 90000, "Department" : "IT" } ] }
{ "_id" : 4, "records" : [ { "Name" : "Kale", "Salary" : 95000, "Department" : "IT" } ] }

我真的很想找到财务和IT部门的工资。 但是具有多个字段的查询会返回所需结果的一部分 -

> db.getCollection('mytest').find({"records.Department": {"$in": ["IT", "Finance"]}}, {"records.$": 1})
    { "_id" : 1, "records" : [ { "Name" : "Joe", "Salary" : 70000, "Department" : "IT" } ] }
    { "_id" : 3, "records" : [ { "Name" : "Sam", "Salary" : 90000, "Department" : "IT" } ] }
    { "_id" : 4, "records" : [ { "Name" : "Janice", "Salary" : 80000, "Department" : "Finance" } ] }

我想知道是否有人可以提供帮助。感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用mongodb $filter运算符来完成此操作。请尝试以下代码:

db.getCollection('mytest').aggregate([
  {  $match: {'records.Department': {$in: ['IT', 'Finance']}}},
  {  $project: { 
      departments: {
        $filter: { 
          input: '$records', 
          as: 'record', 
          cond: {
            $or: [
              {$eq: ['$$record.Department', "IT"]}, 
              {$eq: ['$$record.Department', "Finance"]}
            ]
          }
        } 
      }
    }
  }
])

对于您的数据,我得到以下结果:

{ "_id" : 1, "departments" : [ { "Name" : "Joe", "Salary" : 70000, "Department": "IT" } ] }
{ "_id" : 3, "departments" : [ { "Name" : "Sam", "Salary" : 90000, "Department": "IT" } ] }    
{ "_id" : 4, "departments" : [ { "Name" : "Janice", "Salary" : 80000, "Department" : "Finance" }, { "Name" : "Kale", "Salary" : 95000, "Department" : "IT" } ] }