2.5.3 MongoDB更新和删除

1、整体更新

参考文档:https://docs.mongodb.com/manual/reference/operator/update/

db.questions.replaceOne({},{})

2、更新字段

db.author.updateOne({"name":"mingson"},
    {
        $set: {"age": 20},
        $inc: {"view", -2}
    }
)

3、字段操作

NameDescription
$currentDate 设置为当前时间
$inc 原子级增减操作
$min 当传入的值比数据库中的值小时才更新
$max 当传入的值比数据库中的值大时才更新
$mul 原子级相乘
$rename 重命名字段
$set 设置字段值
$setOnInsert 仅当
$unset 移除字段
db.questions.updateOne({"tags": {$in: ["c#"]}},
    {
        $inc: {"view": NumberInt(-2)},
        $set: {"title": "第一个问题updated"}
    }
)

4、数组操作

NameDescription
$ 更新数组的第一个元素
$[] 更新数组的所有元素
array.[index] 更新指定下标元素
$addToSet 添加元素到数组(当元素不存在于原来的数组当中)
$pop 移除第一个或者最后一个元素
$pull 移除符合条件的数组元素
$pullAll 移除指定元素
$push 添加到最后
$each 添加多个元素
$position 指定插入的位置
$slice 对数据切割
$sort 对数组排序
$[] 更新指定条件的元素
// 把第一个包含 test2 的数组的元素改为 test3,即把数组元素里面第一个 test2 改为 test3,而不是数组的第一个元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.$": "test3"}})

// 更新所有元素,所有 test2 更新为 test3
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.$[]": "test3"}})

// 更新指定下标元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.2": "c#"}})

// 添加元素到数组(当元素不存在于原来的数组当中)
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$addToSet: {"tags": "c#"}})

// 移除第一个
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$pop: {"tags": -1}})

// 移除最后一个元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$pop: {"tags": 1}})

// 移除符合条件的数组元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$pull: {"tags": {$in: ["c#"]}}})

// 移除指定元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$pullAll: {"tags": ["test3", "asp.net core"]})

// 添加到最后
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$push: {"tags": "test3"})

// 添加多个元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$each: {"tags": ["c#", "test3"]})

// 指定插入的位置
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$push: {"tags": {$each: ["c#", "test3"], $position: 0}})

// 对数据切割,对数组排序
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
       }
     }
   }
)

// 更新指定条件的元素,把 answers 中 content 为 回答一 的设置为 回答
db.questions.updateOne({"tags": {$in: ["test2"]}}, {set: {"answers.$[elem].content": "回答", {"arrayFilters": [{"elem.content": "回答一"}]}}})

5、删除

参考文档:https://docs.mongodb.com/manual/tutorial/remove-documents/

db.inventory.deleteOne( { status: "D" } )

db.inventory.deleteMany({ status : "A" })
原文地址:https://www.cnblogs.com/duyao/p/14329320.html