Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (4k points)

 I can achieve this output using this command in mongo shell:

db.people.aggregate([
    { 
        $project: { 
            hobbies: { 
                $filter: { 
                    input: "$hobbies", 
                    as: "hobby", 
                    cond: { $eq: ["$$hobby.regular", true] } 
                }
            },
            name: 1,
            age: 1
        }
    }, 
    { 
        $project: { 
            "hobbies.name": 1, 
            "hobbies.type": 1, 
            name: 1,
            age: 1
        } 
    }
])

As you can see, I had to use two $project operators in sequence and I think this smells bad.

Is there a way to achieve the same result with another query that does not use the same operator twice and in sequence?

1 Answer

0 votes
by (8.7k points)

This can be easily achieved by wrapping the filter expression inside the map for mapping out  the  output values as:

db.people.aggregate([

  {

    "$project": {

      "name": 1,

      "age": 1,

      "hobbies": {

        "$map": {

          "input": {

            "$filter": {

              "input": "$hobbies",

              "as": "hobbyf",

              "cond": "$$hobbyf.regular"

            }

          },

          "as": "hobbym",

          "in": {

            "name": "$$hobbym.name",

            "type": "$$hobbym.type"

          }

        }

      }

    }

  }

])

To get more insight about it, check out the MongoDB tutorial by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...