.NET 云原生架構(gòu)師訓(xùn)練營(模塊二 基礎(chǔ)鞏固 MongoDB 更新和刪除)--學(xué)習(xí)筆記
2.5.4 MongoDB -- 更新和刪除
整體更新
更新字段
字段操作
數(shù)組操作
刪除
https://docs.mongodb.com/manual/reference/operator/update/
updateOne
updateMany
replaceOne
整體更新
db.questions.replaceOne({},{})
更新字段
db.author.updateOne({"name":"mingson"},
{
$set: {"age": 20},
$inc: {"view", -2}
}
)
字段操作
| Name | Description |
|---|---|
| $currentDate | 設(shè)置為當(dāng)前時間 |
| $inc | 原子級增減操作 |
| $min | 當(dāng)傳入的值比數(shù)據(jù)庫中的值小時才更新 |
| $max | 當(dāng)傳入的值比數(shù)據(jù)庫中的值大時才更新 |
| $mul | 原子級相乘 |
| $rename | 重命名字段 |
| $set | 設(shè)置字段值 |
| $setOnInsert | 僅當(dāng) |
| $unset | 移除字段 |
db.questions.updateOne({"tags": {$in: ["c#"]}},
{
$inc: {"view": NumberInt(-2)},
$set: {"title": "第一個問題updated"}
}
)
數(shù)組操作
| Name | Description |
|---|---|
| $ | 更新數(shù)組的第一個元素 |
| $[] | 更新數(shù)組的所有元素 |
| array.[index] | 更新指定下標(biāo)元素 |
| $addToSet | 添加元素到數(shù)組(當(dāng)元素不存在于原來的數(shù)組當(dāng)中) |
| $pop | 移除第一個或者最后一個元素 |
| $pull | 移除符合條件的數(shù)組元素 |
| $pullAll | 移除指定元素 |
| $push | 添加到最后 |
| $each | 添加多個元素 |
| $position | 指定插入的位置 |
| $slice | 對數(shù)據(jù)切割 |
| $sort | 對數(shù)組排序 |
| $[ |
更新指定條件的元素 |
// 把第一個包含 test2 的數(shù)組的元素改為 test3,即把數(shù)組元素里面第一個 test2 改為 test3,而不是數(shù)組的第一個元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.$": "test3"}})
// 更新所有元素,所有 test2 更新為 test3
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.$[]": "test3"}})
// 更新指定下標(biāo)元素
db.questions.updateOne({"tags": {$in: ["test2"]}}, {$set: {"tags.2": "c#"}})
// 添加元素到數(shù)組(當(dāng)元素不存在于原來的數(shù)組當(dāng)中)
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}})
// 移除符合條件的數(shù)組元素
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}})
// 對數(shù)據(jù)切割,對數(shù)組排序
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 為 回答一 的設(shè)置為 回答
db.questions.updateOne({"tags": {$in: ["test2"]}}, {set: {"answers.$[elem].content": "回答", {"arrayFilters": [{"elem.content": "回答一"}]}}})
刪除
https://docs.mongodb.com/manual/tutorial/remove-documents/
db.inventory.deleteOne( { status: "D" } )
db.inventory.deleteMany({ status : "A" })
課程鏈接
.NET云原生架構(gòu)師訓(xùn)練營講什么,怎么講,講多久
評論
圖片
表情
