How can I write query in mongodb?

I have a collection of mongodb like this :

[{
   "_id":"ObjectId(""51780fb5c9c41825e3e21fc4"")",
   "name":"CS 101",
   "students":[
      {
         "name":"raj",
         "year":2016
      },
      {
         "name":"rahul",
         "year":2017
      },
      {
         "name":"anil",
         "year":2018
      }
   ]
},
{
   "_id":"ObjectId(""51780fb5c9c41825e3e21fs4"")",
   "name":"CS 102",
   "students":[
      {
         "name":"mukesh",
         "year":2016
      },
      {
         "name":"mohan",
         "year":2017
      },
      {
         "name":"mangal",
         "year":2018
      }
   ]
}
]

I’ve been looking for similar questions like this one: Mongo db – Querying nested array and objects but in that question they’re looking for a specific element inside the “messages” object (in my case) for example. Same as in this other question: Query for a field in an object in an array with Mongo? where they’re using $mapan d I don’t think it fits my needs.

The documents to find have this structure:

[{
   "_id":"ObjectId(""51780fb5c9c41825e3e21fc4"")",
   "name":"CS 101",
   "students":[
    "raj","rahul","anil"
   ]
},
{
   "_id":"ObjectId(""51780fb5c9c41825e3e21fs4"")",
   "name":"CS 102",
   "students":[
     "mukesh","mohan","mangal"
   ]
}
]

how to solve this?

Answer

From the question and datasets, you are trying to return students with an array of student’s name (string) instead of the array of student object.

Use $project to display students as students.name array.

db.collection.aggregate([
  {
    $project: {
      "_id": "$_id",
      "name": "$name",
      "students": "$students.name"
    }
  }
])

Sample Solution 1 on Mongo Playground

OR

Use $set to replace the students field with students.name array.

db.collection.aggregate([
  {
    $set: {
      "students": "$students.name"
    }
  }
])

Sample Solution 2 on Mongo Playground