🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
更新由`update`、`updateOne`、`updateMany`函数完成,总共分为两种更新策略: (1)只更新指定字段,不影响其它字段 (2)更新指定字段,删除没有指定的字段 基本语法: ```js db.collection_name.update( <query>, 更新条件 <update>, 更新操作 { upsert:<boolean>, 如果为true,当没有匹配的文档时则插入该文档; 如果为false,则不插入,默认为false multi:<boolean>, 如果为true,则更新符合条件的所有记录,相当于updateMany; 如果为false,则只更新找到的第一条记录,相当于updateOne 默认为 false writeConcern 抛出异常级别 } ) ``` 测试用例: ```sql > for(let i=1; i<=30; i++) db.goods.insertOne({"_id":i,"name":"apple"+i,"addr":"苹果旗舰店"+i,"contry":"中国"+i,"price":5000+i*100}) { "acknowledged" : true, "insertedId" : 30 } > db.goods.find() { "_id" : 1, "name" : "apple1", "addr" : "苹果旗舰店1", "contry" : "中国1", "price" : 5100 } { "_id" : 2, "name" : "apple2", "addr" : "苹果旗舰店2", "contry" : "中国2", "price" : 5200 } ... { "_id" : 30, "name" : "apple30", "addr" : "苹果旗舰店30", "contry" : "中国30", "price" : 8000 } ``` <br/> **1. 更新指定字段,不影响其它字段** ```sql # $set 是更新指令,$inc是加法 > db.goods.update({"_id":1}, {$set:{contry:"美国"}, $inc:{price: 900}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.goods.find() { "_id" : 1, "name" : "apple1", "addr" : "苹果旗舰店1", "contry" : "美国", "price" : 6000 } { "_id" : 2, "name" : "apple2", "addr" : "苹果旗舰店2", "contry" : "中国2", "price" : 5200 } { "_id" : 3, "name" : "apple3", "addr" : "苹果旗舰店3", "contry" : "中国3", "price" : 5300 } ``` <br/> **2. 更新指定字段,没有指定的清除(主键`_id`除外)** ```sql > db.goods.update({"_id":1}, {contry: "中国"}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.goods.find() { "_id" : 1, "contry" : "中国" } { "_id" : 2, "name" : "apple2", "addr" : "苹果旗舰店2", "contry" : "中国2", "price" : 5200 } { "_id" : 3, "name" : "apple3", "addr" : "苹果旗舰店3", "contry" : "中国3", "price" : 5300 } ```