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

194
Views
Get Specific Values from MongoDB

I am new to Mongo so any help is appreciated.

I have a User object and in it multiple more objects which are hosting client data based on the User's interaction with each one.

This is how it looks like

db.users.findOne(
  {"clients.clientId":35},
  {"clients.clientId":1}
)
{
  "_id" : ObjectId("586670e6ce9287cf6d197d14"),
  "clients" : [ 
        { "clientId" : 35 },
        { "clientId" : 67 }, 
        { "clientId" : 73 }, 
        { "clientId" : 78 }, 
        { "clientId" : 82 } 
  ] 
}

As you can see from my query, it returns a User that has data from client 35 but also returns data from every other client.

How can I access only the data from client 35?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You have an embedded array of documents on the clients key.

Your query projection {"clients.clientId":1} states that the query should return only that key, clients key. Your clients field is an array, therefore all embedded documents from the array will be extracted (projected).

When you want only one element in the array to be displayed, the one defined in the query i.e. the client with id 35 {"clients.clientId":35}, need to use the projection positional operator $:

db.users.findOne({"clients.clientId":35},{"clients.$":1})

Result:

{
    "_id" : ObjectId("586670e6ce9287cf6d197d14"),
    "clients" : [
        {
            "clientId" : 35
        }
    ]
}

Note: using $ operator, it will project only the first element in the array that matches the query; if you have more documents in the array having the same value, only the first will be displayed.

over 4 years ago · Santiago Trujillo 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!