I'm trying to get the parent of an element in a document but I'm not quite sure how. Could I please get some help?
This is what my collection looks like
students:Array
0:Object{
age:21
studentName:"ABC"
height: "178"
},
1:Object{
age:25
studentName:"DSA"
height: "185"
}
I want to be able to find
0:Object{
age:21
studentName:"ABC"
height: "178"
}
When I search for studentName = "ABC"
Could I please get some help?
CodePudding user response:
if you first fetch data from mongodb then you can do it:
const urStudent = students.filter((student)=> student.studentName === "ABC")
but if you want just to fetch a certain student, so you should change the query. something like that:
db.Students.findOne({studentName:"ABC"}).then((res)=>{...})
CodePudding user response:
Query1
(using find)
db.collection.find({
students: {
$elemMatch: {
studentName: "ABC"
}
}
},
{
"students.$": 1
})
Query2
(using aggregation)
aggregate(
[{"$project":
{"_id": 0,
"student":
{"$arrayElemAt":
[{"$filter":
{"input": "$students",
"cond": {"$eq": ["$$this.studentName", "ABC"]}}},
0]}}}])