Mongodb 使用pull查找并更新,并获得所提取的文档作为回报
这是我的收藏Mongodb 使用pull查找并更新,并获得所提取的文档作为回报,mongodb,Mongodb,这是我的收藏 [ {_id:1, persons:[{name:"Jack",age:12},{name:"Ma",age:13}] } ] 我想通过拉取删除{name:“Jack”,年龄:12}中的人员,但我还想在拉取完成后,我将返回拉取的{name:“Jack”,年龄:12}。我该怎么做 我想这样做 db.getCollection('test').findOneAndUpdate({_id:1},{$pull:{"per
[
{_id:1,
persons:[{name:"Jack",age:12},{name:"Ma",age:13}]
}
]
我想通过拉取删除{name:“Jack”,年龄:12}
中的人员
,但我还想在拉取完成后,我将返回拉取的{name:“Jack”,年龄:12}
。我该怎么做
我想这样做
db.getCollection('test').findOneAndUpdate({_id:1},{$pull:{"persons":{name:"Jack"}}},
{projection:{"person":{
$filter : {
input: "$persons",
as : "ele",
cond : {$eq : ["$$ele.name","Jack"]}
}
}}})
您可以使用
$reduce
,因为$filter
将返回数组,也将支持MongoDB 4.4
db.getCollection('test').findOneAndUpdate({_id:1},
{ $pull: { "persons": { name: "Jack" } } },
{
projection: {
"person":{
$reduce: {
input: "$persons",
initialValue: {},
in: { $cond: [{$eq: ["$$this.name","Jack"]}, "$$this", "$$value"] }
}
}
}
}
)
您可以使用
$reduce
,因为$filter
将返回数组,也将支持MongoDB 4.4
db.getCollection('test').findOneAndUpdate({_id:1},
{ $pull: { "persons": { name: "Jack" } } },
{
projection: {
"person":{
$reduce: {
input: "$persons",
initialValue: {},
in: { $cond: [{$eq: ["$$this.name","Jack"]}, "$$this", "$$value"] }
}
}
}
}
)
你能在操场上给我看一下这个吗,如果有效的话,我会把它标记为答案吗?
“errmsg”:“不支持的投影选项:人:{$reduce:{input:\“$persons\”,initialValue:{},in:{$cond:[{$eq:[\“$$this.name\”,\'Jack\']},\“$$this\”,\“$$value\]}}}}}”
你的mongodb的版本是什么?看看这个,这个版本是4.2Ok,所以它只支持4.4版本,你能在游戏中给我看一下吗,如果有效的话,我会把它标记为答案?“errmsg”:“不受支持的投影选项:person:{$reduce:{input:\'$persons\”,initialValue:{},in:{$cond:[{$eq:[\'$$this.name\',\'Jack\']},\'$$this\',“$$value\]}”
mongodb的版本是什么?看看这个,这个版本是4.2Ok,所以它只支持4.4版本