0

I have two queries as such:

db.employee.aggregate({$match: {lname:"Smith"}}, {$project: {"SSN": 1, "_id": 0}})
db.works_on.aggregate({$match: {essn: 123456789}}, {$project: {"pno": 1, "_id": 0}})

Is there a way that I can make this into a single query where the essn number is replaced with the SSN output by the first aggregate?

zekrofire
  • 51
  • 7
  • Does this answer your question? [How to join multiple collections with $lookup in mongodb](https://stackoverflow.com/questions/35813854/how-to-join-multiple-collections-with-lookup-in-mongodb) – whoami - fakeFaceTrueSoul Mar 25 '20 at 15:06

1 Answers1

1

Yes, you can do it using $lookup. Try the below query.

db.employee.aggregate([
    {
        $lookup:{
            from: "works_on",       
            localField: "SSN",   
            foreignField: "essn", 
            as: "employee_works"         
        }
    },
    {   $unwind:"$employee_works" }, 
    {   
        $project:{
            lname: 1,
            SSN: 1,
            pno : "$employee_works.pno",
        } 
    }
]);
RLD
  • 1,867
  • 3
  • 15
  • 20