Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb : array element projection with findOneAndUpdate doesn't work?

I am using Mongoose and I'm trying to update an array element and get it back updated. This is my document structure :

{   name:String,
    friends:[
        {   name:String,
            age:Number
        }
    ]
}

When I execute the following query I get all the friends in the result but I only want to get 25 year old friends back :

theCollection.findOneAndUpdate(
    {   name : 'cherif',
        'friends.name':'kevin'
    },
    {   $set:{
            'friends.$.age':25
        }
    },
    {   friends:
        {   $elemMatch:
            {   age : 25 } 
        }
    },
    function(err,result){
        if (!err) {
            console.log(result);
        }});
like image 525
Cherif Avatar asked May 04 '26 02:05

Cherif


1 Answers

As the docs for findOneAndUpdate specify, you need to include your projection object as the select property of the options parameter:

theCollection.findOneAndUpdate(
    {   name : 'cherif',
        'friends.name':'kevin'
    },
    {   $set:{
            'friends.$.age':25
        }
    },
    {   select: { 
            friends: {
               $elemMatch: 
               {   age : 25 } 
            }
        }
    },
    function(err,result){
        if (!err) {
            console.log(result);
        }
    });
like image 136
JohnnyHK Avatar answered May 05 '26 16:05

JohnnyHK