Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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
Arrays 使用$in和$addtoSet Mongodb更新阵列_Arrays_Mongodb_Mongodb Update - Fatal编程技术网

Arrays 使用$in和$addtoSet Mongodb更新阵列

Arrays 使用$in和$addtoSet Mongodb更新阵列,arrays,mongodb,mongodb-update,Arrays,Mongodb,Mongodb Update,我正在使用$in和$addToSet更新集合中的数组。假设我有这样的文件 { _id: objectId(1), //this is just an example id names: ['harry', 'hermione'] }, { _id: objectId(2), names: ['ron'] }, { _id: objectId(3), names: ['dumbledoor'] } 我想更新所有这些文档,这样我就有了一个ID数组

我正在使用
$in
$addToSet
更新集合中的数组。假设我有这样的文件

{ 
    _id: objectId(1), //this is just an example id
    names: ['harry', 'hermione']
},
{
    _id: objectId(2),
    names: ['ron']
},
{
    _id: objectId(3),
    names: ['dumbledoor']
}
我想更新所有这些文档,这样我就有了一个ID数组

var arr_ids = [1, 2];
然后像这样使用数组
map

var ids = arr_ids.map(function(id) { return mongoose.Types.ObjectId(id); });
更新我的收藏中的所有文档

db.update( { _id: { $in: ids } }, { $addToSet: { name : 'draco' } }, 
    function(err, results) {
      if(err) console.log(err);
      console.log(results);
    }
);
我使用
$in
$addToSet
中的
,它可以工作并更新文档,但只更新最后一个文档

{ 
    _id: objectId(1), //this is just an example id
    names: ['harry', 'hermione']
},
{
    _id: objectId(2),
    names: ['ron', 'draco'] // it only update this document.
},
{
    _id: objectId(3),
    names: ['dumbledoor']
}

我不知道为什么。我不想创建一个for循环来单独更新它,但在我看来这是我最后的选择。请帮帮我。谢谢

像这样用
multi:true
试试看

db.update( /*query*/, { $addToSet: { names : 'draco' } }, {multi:  true} ...
有关文档,请参阅和