Skip to content

Latest commit

 

History

History
67 lines (66 loc) · 960 Bytes

exer1.md

File metadata and controls

67 lines (66 loc) · 960 Bytes

MongoDB Aggregation Pipelines

  • Count no. of active users
[
 {
   $match: {
     isActive: true,
   },
 },
 {
   $count: "activeUsers",
 },
]
  • What is a average age of all users
[
  {
    $group: {
      //to get entire document
      _id: null,
      averageAge:{
        $avg: "$age"
      }
    }
  }
]
  • What is a average age of both genders
[
  {
    $group: {
      //to get entire document
      _id: "$gender",
      averageAge:{
        $avg: "$age"
      }
    }
  }
]
  • List the top 5 common fruits among the users
[//stage 1
  {
    $group: {
      _id: "$favoriteFruit",
      count:{
        //increment by 1 on finding a person with this fruit preference
        $sum: 1
      }
    },
  },
  //stage 2
  {
    $sort: {
      count: 1
    }
  },
  //stage3-find top k
  {
    $limit: 2
  }
]