2

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);
        }});

1 Answer 1

11

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);
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to use $ projection here? For example Doc.findOneAndUpdate({ _id: id, 'comments._id': cmtId }, {...}, { select: 'comments.$': 1 }). I've tried this but strangely it returned { comments: [{}, {}, {}], _id:... }
@KwiZ Did you ever find a solution for this? I'm trying to use $ projection in the same way but with no luck!
@admrply Go ahead and post a new question with the full details about what you're trying to do.
the answer to @KwiZ is use 0 instead of $ ( { select: 'comments.0': 1 })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.