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

狂风中的少年 提交于 2019-12-18 04:25:13

问题


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:


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


来源:https://stackoverflow.com/questions/18986505/mongodb-array-element-projection-with-findoneandupdate-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!