$ lookup in db.createView ()

0

I have a database with two collections : companies and people .

And I want to create a view named "peopleSectors" from collection people .

db.createView (
   "peopleSectors",
   "people",
   [
     { $lookup: { from: "companies", localField: "company_id", foreignField: "_id", as: "company_field" } },
     { $project: 
          { "_id": 0, 
            "first_name": 1, 
            "last_name": 1, 
            "job": 1,  
            "company": '$employer', 
            "sector": /* aqui mora o problema */
          }
     }
   ]
)

But within $project , when I create the schema view , I want your "sector" field equal to the collection companies sector field within $ lookup

How to access this collection ? I know that in order to access collection the view , just put dollar ahead, but the other?

Example Schema - "people"

{
    "_id" : ObjectId("57d7a121fa937f710a7d486e"),
    "last_name" : "Pham",
    "quote" : "Aliquam est reiciendis alias neque ad.",
    "job" : "Counselling psychologist",
    "ssn" : "401-31-6615",
    "address" : {
        "city" : "Burgessborough",
        "street" : "83248 Woods Extension",
        "zip" : "47201"
    },
    "first_name" : "Yvonne",
    "company_id" : ObjectId("57d7a121fa937f710a7d486d"),
    "employer" : "Terry and Sons",
    "birthday" : ISODate("2011-03-17T11:21:36Z"),
    "email" : "[email protected]"
}

Example Schema - "companies"

{
    "_id" : ObjectId("57d7a121fa937f710a7d486d"),
    "sector" : "Wholesale",
    "name" : "Terry and Sons",
    "mission" : "implement frictionless systems",
    "address" : {
        "city" : "Lake Meaganton",
        "state" : "Idaho",
        "street" : "211 Diane Shoals",
        "zip" : "10914-3394"
    },
    "logo" : "http://dummyimage.com/687x376"
}
    
asked by anonymous 23.12.2016 / 18:59

1 answer

1

Each stage of aggregation receives the result of the previous one. Therefore, just use dot-notation to access the desired field.

Try something like:

[
  {
    $lookup: {
      from: "companies",
      localField: "company_id",
      foreignField: "_id",
      as: "related_companies"
    }
  },
  {
    $project: {
      "_id": 0,
      "first_name": 1,
      "last_name": 1,
      "job": 1,
      "company": '$related_companies.name',
      "sector": '$related_companies.sector'
    }
  }
]
    
26.12.2016 / 17:14