2

My database structure is looking like this :

    {
        'name' : 'entry one'
        'project' : 
            [
                {companyName : 'a name', contactPerson : [{ work_email: 'test@test.com'}] } , 
                {companyName : 'a name1', contactPerson : [{ work_email: 'test1@test.com'}] } , 
                {companyName : 'a name2', contactPerson : [{ work_email: 'test2@test.com'}] } 
            ]
    }



    {
        'name' : 'entry 2'
        'project' : 
            [
                {companyName : 'another name', contactPerson : [{ work_email: 'testing@test.com'}] } , 
                {companyName : 'another name1', contactPerson : [{ work_email: 'testing1@test.com'}] } , 
                {companyName : 'another name 2', contactPerson : [{ work_email: 'testing2@test.com'}] } 
            ]
    }

What i want is to find the companyName that belongs to a given work_email. So if the work_email is test@test.com the company name that should be returned should be 'a name'

So the query i built with mongoose is this :

const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test@test.nl'} , 'project.companyName'); 

But this is returning all company names (from entry one) not the single one i am looking for.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82

1 Answers1

1

Filtering will always return whole document. You need to use projection to "reshape" it. You can consider the $ (projection) operator:

const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test@test.nl'} , { 'project.$': 1 }); 

Mongo Playground

mickl
  • 48,568
  • 9
  • 60
  • 89
  • isnt it `project.$.companyName`? because he just wants the name – bill.gates Aug 05 '20 at 11:55
  • 1
    This is super helpful i didn't know about this yet , thank you so much – Kevin.a Aug 05 '20 at 11:56
  • @Ifaruki yeah i can do that last step myself , thankfully ! – Kevin.a Aug 05 '20 at 11:57
  • Is it possible to update the found entry ? Let's say i want to change the companyName of the found entry. How would i do this ? Or is there an article or something you can redirect me to. – Kevin.a Aug 05 '20 at 15:56
  • @Kevin.a sure, you can have a look here: https://stackoverflow.com/questions/55917114/mongoose-query-deeply-nested-objects/55917180#55917180 – mickl Aug 05 '20 at 16:01