How to select the array element

{
“_id” : ObjectId(“606b7031a0ccf722226a85ae”),
“groupId” : ObjectId(“5f06cca74e51ba15f5167b86”),
“insertedAt” : “2021-04-05T20:16:49.893343Z”,
“isActive” : true,
“staffId” : [
“606b6b44a0ccf72222ce375a”
],
“subjectName” : “English”,
“teamId” : ObjectId(“6069a6a9a0ccf704e7f4b537”),
“updatedAt” : “2021-04-05T20:16:49.893382Z”
}
{
“_id” : ObjectId(“606b7046a0ccf72222c00c2f”),
“groupId” : ObjectId(“5f06cca74e51ba15f5167b86”),
“insertedAt” : “2021-04-05T20:17:10.144521Z”,
“isActive” : true,
“staffId” : [
“606b6c34a0ccf72222c5a4df”,
“606b6c48a0ccf722228aa035”
],
“subjectName” : “Maths”,
“teamId” : ObjectId(“6069a6a9a0ccf704e7f4b537”),
“updatedAt” : “2022-04-29T07:57:31.072067Z”,
“syllabus” : [
{
“chapterId” : “626b9b94ae6cd2092024f3ee”,
“chapterName” : “chap1”,
“topicsName” : [
{
“topicId” : “626b9b94ae6cd2092024f3ef”,
“topicName” : “1.1”
},
{
“topicId” : “626b9b94ae6cd2092024f3f0”,
“topicName” : “1.2”
}
]
},
{
“chapterId” : “626b9b94ae6cd2092024f3f1”,
“chapterName” : “chap2”,
“topicsName” : [
{
“topicId” : “626b9b94ae6cd2092024f3f2”,
“topicName” : “2.1”
},
{
“topicId” : “626b9b94ae6cd2092024f3f3”,
“topicName” : “2.2”
}
]
}
]
}

The query to fetch syllabus with chapter id
db.subject_staff_database.find( { “_id” : ObjectId( “606b7046a0ccf72222c00c2f” )},{“syllabus” : {"$elemMatch" : { “chapterId”:“626b9b94ae6cd2092024f3ee”} } } ).pretty()

output

{
“_id” : ObjectId(“606b7046a0ccf72222c00c2f”),
“syllabus” : [
{
“chapterId” : “626b9b94ae6cd2092024f3ee”,
“chapterName” : “chap1”,
“topicsName” : [
{
“topicId” : “626b9b94ae6cd2092024f3ef”,
“topicName” : “1.1”
},
{
“topicId” : “626b9b94ae6cd2092024f3f0”,
“topicName” : “1.2”
}
]
}
]
}

Now I want to select topicsName array first elemet data along with chapterId and chapterName how to achive it

Read Formatting code and log snippets in posts and re-publish your documents in a way we can use them to experiment.

Hi @Prathamesh_N ,

What you are looking for is called positional projection :

Where you can project first element that match a query :

"syllabus.topicNames.$" : 1

Or use aggregation

{ $addFields: {
    "syllabus.topicNames": { $first: "$syllabus.topicNames" }
}}

Thanks
Pavel