Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Finding parent of an element in mongodb

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)=>{...})
about 4 years ago · Juan Pablo Isaza Report

0

Query1
(using find)

Test code here

db.collection.find({
  students: {
    $elemMatch: {
      studentName: "ABC"
    }
  }
},
{
  "students.$": 1
})

Query2
(using aggregation)

Test code here

aggregate(
[{"$project": 
   {"_id": 0,
    "student": 
    {"$arrayElemAt": 
     [{"$filter": 
        {"input": "$students",
          "cond": {"$eq": ["$$this.studentName", "ABC"]}}},
      0]}}}])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!