MongoDB更新数组操作符

set

1.set如果不存在,就创建

db.students.update(
{stuname:"zzxb"},
{$set:{aihao:"篮球,足球"}}
)

db.students.update(
{stuname:"小黑"},
{$set:{aihao:["篮球","足球"]}}
)

db.students.update(
{stuname:"小黑"},
{$push:{aihao:"乒乓球"}}
)

unset

2.unset删除字段

db.students.update(
{stuname:"小黑"},
{$unset:{Aihao:null}}
)

push

一. $ push操作符添加指定的值到数组中,$push操作符有如下的格式:

{ $push: { <field1>: <value1>, ... } }

指定一个在一个内嵌文档中或者在一个数组中,使用点号分开
$ push修饰符可以和 e a c h each、 slice、 s o r t sort、 position修饰符一起使用,当使用这些修饰符的时候$push操作符有如下格式:

{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }

如下语句添加89到scores字段中

db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)

添加多个值到数组中
使用$ push操作符和$ each修饰符一起添加多个值到数组字段中。

如下例子添加数组[ 90, 92, 85 ]中的每个元素到数组scores字段中,对于字段name等于joe的文档:

db.students.update(
   { name: "joe" },
   { $push: { scores: { $each: [ 90, 92, 85 ] } } }
)

$push操作符和多个操作符一起使用
集合students有如下文档

{
   "_id" : 5,
   "quizzes" : [
      { "wk": 1, "score" : 10 },
      { "wk": 2, "score" : 8 },
      { "wk": 3, "score" : 5 },
      { "wk": 4, "score" : 6 }
   ]
}

如下$push操作符使用:

$each修饰符添加多个值到quizzes数组中;

$sort修饰符将数组quizzes中的元素按照score元素降序排列;

$slice修饰符只留下数组quizzes中前三个排序元素

db.students.update(
   { _id: 5 },
   {
     $push: {
       quizzes: {
          $each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],
          $sort: { score: -1 },
          $slice: 3
       }
     }
   }
)

操作的结果是只留下quizzes数组中分数最高的三个

{
  "_id" : 5,
  "quizzes" : [
     { "wk" : 1, "score" : 10 },
     { "wk" : 2, "score" : 8 },
     { "wk" : 5, "score" : 8 }
  ]
}

addToSet

db.posts.update(
{title:"java编程指南"},
{$addToSet:{likes:{"name","cc"}}}
)

update

MongoDB 使用 update() 和 save() 方法来更新集合中的文档

update() 方法

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

参数说明

  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如 , , inc…)等,也可以理解为sql update查询内set后面的
  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
  • writeConcern :可选,抛出异常的级别。

实例
我们在集合 col 中插入如下数据:

>db.col.insert({
    title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '教程',
    url: 'http://www.xxx.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

接着我们通过 update() 方法来更新标题(title):

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   # 输出信息
> db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "教程",
        "url" : "http://www.xxxxx.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>

可以看到标题(title)由原来的 “MongoDB 教程” 更新为了 “MongoDB”。

以上语句只会修改第一条发现的文档,如果你要修改多条相同的文档,则需要设置 multi 参数为 true。

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})

save() 方法

save() 方法通过传入的文档来替换已有文档。语法格式如下:

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

参数说明:

  • document : 文档数据。
  • writeConcern :可选,抛出异常的级别。

实例
以下实例中我们替换了 _id 为 56064f89ade2f21f36b03136 的文档数据:

>db.col.save({
    "_id" : ObjectId("56064f89ade2f21f36b03136"),
    "title" : "MongoDB",
    "description" : "MongoDB 是一个 Nosql 数据库",
    "by" : "R",
    "url" : "http://www.xxx.com",
    "tags" : [
            "mongodb",
            "NoSQL"
    ],
    "likes" : 110
})

替换成功后,我们可以通过 find() 命令来查看替换后的数据

>db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "Runoob",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "NoSQL"
        ],
        "likes" : 110
}
>
更多实例

只更新第一条记录:

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

全部更新:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

只添加第一条:

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

全部添加进去:

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

全部更新:

db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );

只更新第一条记录:

db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );
update students set age = 20 where stuname = "xiaoli"


db.students.update(
{stuname:"xiaoli"}, //条件
{$set:{age:20}}//更新 
)

db.students.update(
{status:"ok"},
{$set:{age:22}}
)

db.students.update(
{status:"ok"},
{$set:{age:19}},
{multi:true} //可选条件:multi:true代表更新多条,false只更新一条
)

db.students.updateMany(
{status:"preding"},
{$set:{age:18}}
)

db.students.updateMany(
{age:{$gte:19}},//条件
{$set:{status:"stop"}}//
)


db.students.updateMany(
{age:{$lte:18}},
{$set:{status:"ok"}}
)

update students set status = "preding" where age = 19 and status = "stop"

db.students.updateMany(
{age:19,status:"stop"},
{$set:{status:"preding"}}
)

update students set age = 18,status = "ok" where stuname = "xiaoli"


db.students.updateMany(
{stuname:"xiaoli"},
{$set:{age:18,status:"ok"}}
)


db.students.save(
{
  _id : objectId("5c91a787eed64703d8481296"),
  stuname: "小黑",
  age:30,
  status:"stop"
}
)

db.students.update(
{stuname:"小黑"},
{$inc:{age:1}}
)
发布了154 篇原创文章 · 获赞 605 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/weixin_39381833/article/details/88886469