Mongodb:使用findOneAndUpdate进行数组元素投影不起作用? [英] Mongodb : array element projection with findOneAndUpdate doesn't work?

查看:69
本文介绍了Mongodb:使用findOneAndUpdate进行数组元素投影不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mongoose,并且正在尝试更新数组元素并使它重新更新. 这是我的文档结构:

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
        }
    ]
}

执行以下查询时,我得到了结果中的所有朋友,但我只想找回25岁的朋友:

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

推荐答案

作为文档对于findOneAndUpdate指定,您需要将投影对象包括为options参数的select属性:

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

这篇关于Mongodb:使用findOneAndUpdate进行数组元素投影不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆