I have following data in my mongoDb database and I want to find the student from the array of students objects by iterating on all my students field of my database with the id the students array objects have.
I want to do it with the help of mongoose please help me find the solution as I am unable to find it.
Here is my database:
[
{
"_id": "637ddf6d68a8284187a4d7e7",
"college": "MIT"
"students": [
{
"name": "Morgan Freeman",
"image": "/public/morg.jpg",
"_id": "637ddf6d68a8284187a4d7e8"
},
{
"name": "John Smith",
"image": "/public/john.jpg",
"_id": "637ddf6d68a8284187a4d7e9"
}
]
},
{
"_id": "637ddf6d68a8284187a4dfhd",
"college": "DOT"
"students": [
{
"name": "Windy rona",
"image": "/public/windy.jpg",
"_id": "637ddf6d68a8284187a4dvh3"
},
{
"name": "Richard",
"image": "/public/richard.jpg",
"_id": "637ddf6d68a8284187a4duhd"
}
]
},
]
I tried using:
database.find({}).select('students').where('_id':req.params.id)
but it didnot work
2
Answers
Well if I understand your question you want to filter the result of the student array that match with the _id of the student that it providing
an aggregation with filter the project must help you.
here an example:
this will give you the following result:
Option 1) Aggregation/$filter mongodb 3.2+ Maybe something like this:
Exaplained:
Playground
Option 2) Find ( find first matching in a document , it will not show if there is other matching with this _id in the same document ):
Explained:
Playground 2