Mongodb:使用 findOneAndUpdate 进行数组元素投影不起作用? [英] Mongodb : array element projection with findOneAndUpdate doesn't work?
本文介绍了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);
}});
推荐答案
As 文档 为 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屋!
查看全文