MongoDB查找然后进行项目

时间:2018-11-27 17:09:08

标签: mongodb mongodb-query aggregation-framework aggregate-functions

我有两个集合- jobs companies –它们具有多对一的关系,因此许多 jobs 存在一条 companies 记录。


jobs 具有以下字段:

  

job_id,company_id,last_updated,j_foo,j_bar


companies 具有以下字段:

  

company_id,名称,some_url,c_foo,c_bar



我现在拥有的查询:

var matchObj = {'company_id':'some_company'};
var lookupObj = {from:'companies',localField:'company_id',foreignField:'company_id',as:'company_info'};
var projectObj = {'job_id':1,'company_id':1,'last_updated':1};
var sortObj = {'last_updated':-1};

jobs.aggregate({$match:queryObj},{$lookup:queryLookup},{$project:queryProject},{$sort:sortObj}).toArray(function(err,results){
  doSomething();
});

返回的数据超出了我的需求

[
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    j_foo: val,
    j_bar: val,
    company_info: [{ 
      company_id: val, name: val, some_url: val, c_foo: val, c_bar: val
    }]  // I don't want company_info as an array ideally,
        // rather just have the object since it's a to-one relationship
        // it's always just one result. This isn't critical,
        // just would be a nicety if you can help with this too
  },
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    j_foo: val,
    j_bar: val,
    company_info: [{ 
      company_id: val, name: val, some_url: val, c_foo: val, c_bar: val
    }]
  }
]

我想要的输出是:

[
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    company_info: { 
      name: val, some_url: val
    }
  },
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    company_info: { 
      name: val, some_url: val
    }
  }
]

如果输出为:

[
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    company_name: val,
    company_some_url: val
  },
  {
    job_id: val,
    company_id: val,
    last_updated: date,
    company_name: val,
    company_some_url: val
  }
]

如何投影查找查询?还是有使用$ addFields的另一种方法?

0 个答案:

没有答案