0

I tried below code but only first match is checked and displayed,others displayed as object, why I am unable to see it in console. I have 3 collections student subject teacher, also made schema for the same. tried aggregation

Student.aggregate([

            {

              $match: { name: 'abcd'}
            },

            {
            $lookup:
             {
               from:'teachers',
               pipeline: [{ $match: { name: 'pqrs' } },],
               as: "teacherLookup"

             }
            },
            {
            $lookup:
             {
               from:'subjects',
               pipeline: [{ $match: { name: 'computer' } }],
               as: "subjectLookup"
             }
            }

          ]).then(function (res) {
            console.log(res); 
            res.forEach(function(students){
              let id = students._id;
              console.log(id+ ' got id ')

            }

    output
    student 
    name:'abcd' -- its fetched and other two not displaying values only shows object
    teacherLookup: [ [Object] ]
    subjectLookup: [ [Object] ]
4
  • Yes, because lookup generates the array output. You need to iterate over it to log. Commented Apr 27, 2020 at 17:02
  • how to specifically fetch only the _id from db with the name given. Commented Apr 27, 2020 at 20:19
  • 1
    { $lookup: { from:'teachers', pipeline: [aggregation{{ $match: { name: 'pqrs' } },{_id:'1'}} ], as: "teacherLookup" } }, Commented Apr 27, 2020 at 20:21
  • tried above but met error Commented Apr 27, 2020 at 20:21

1 Answer 1

1

You were there just to project something you have to use $project stage.

Here I'm adding the query:

Student.aggregate([
  {
    $match: { name: 'abcd'}
  },
  {
    $lookup:{
       from:'teachers',
       pipeline: [
        { 
          $match: { name: 'pqrs' } 
        },
        {
          $project:{
            "_id":1
          }
        }
       ],
       as: "teacherLookup"
    }
  },
  {
    $lookup:
     {
       from:'subjects',
       pipeline: [
        { 
          $match: { name: 'computer' } 
        },
        {
          $project:{
            "_id":1
          }
        }
       ],
       as: "subjectLookup"
     }
  }
])

For more about $project refer here.

Hope this will help :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.