Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 使用pull查找并更新,并获得所提取的文档作为回报_Mongodb - Fatal编程技术网

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版本