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集合_Mongodb - Fatal编程技术网

更新Mongodb集合

更新Mongodb集合,mongodb,Mongodb,我想更改所有文档中2个属性的值,其中_id小于200,新值将是随机值(从1到15)。所以我开始写这个脚本,但不起作用: db.myCollection.update( { _id: { $lt: 200 }}, { tilte1 : "hello"+Math.floor(Math.random()*16), title2 : ["hello"+Math.floor(Math.random()*16),"hello"+Math.floor(Math.

我想更改所有文档中2个属性的值,其中_id小于200,新值将是随机值(从1到15)。所以我开始写这个脚本,但不起作用:

    db.myCollection.update(
    { _id: { $lt: 200 }},

   {

     tilte1 : "hello"+Math.floor(Math.random()*16),

     title2 : ["hello"+Math.floor(Math.random()*16),"hello"+Math.floor(Math.random()*16),"hello"+Math.floor(Math.random()*16)], 

   })
谢谢你的帮助

db.myCollection.update(
    { _id: { $lt: 200 }},
    {
      $set : { title1 : "hello"+Math.floor(Math.random()*16) ,
               title2 : ["hello"+Math.floor(Math.random()*16),"hello"+Math.floor(Math.random()*16),"hello"+Math.floor(Math.random()*16)]}

    }, {multi: true});
您需要添加
{multi:true}
来更新所有文档,否则它将只更新第一个文档

您在
标题1
字段中有输入错误。确保其
倾斜1
标题1

如果要保留文档中以前的字段,请使用
$set
。根据您当前的查询,它将仅用这两个字段替换文档和


请记住:
多次更新仅适用于$operators

文档的_id属性不是整数。它是一个
ObjectId
(生成的12字节BSON类型:timestamp、machine ID、process ID和process local incremental counter)在我的例子中,它是一个整数,因为我强制它,创建集合时。@SimoSlash如果没有$operator,您不能使用多文档更新。假设您试图在每个文档上将这些属性设置为不同的随机值,您需要一次更新一个文档。@JohnnyHK完全正确,否则Math.random将为所有文档返回相同的值。很好,非常感谢。我有一个与随机相关的小问题,我在所有文档中都得到了相同的值:“title1”:“hello12”和“title2”:[“hello6”、“hello3”、“hello15”],您需要使用循环一次更新一个文档。否则math.random将始终提供相同的值。