MongoDB 文档更新update

无论是关系型数据库还是非关系型数据库,数据插入数据库,都会有更新的需求。与其他数据库数据一致,mongodb提供update方法来更新数据库中的数据。

更新方法

mongodb为不同的场景提供更新方法

  • db.collection.updateOne()更新一条数据
  • db.collection.updateMany()更新多条数据
  • db.collection.replaceOne(),替换文档中除了_id字段外的所有字段。

还有一些和数据查找结合使用的方法

  • db.collection.findOneAndReplace()
  • db.collection.findOneAndUpdate()
  • db.collection.findAndModify()
  • db.collection.bulkWrite()

语法

复制代码
db.collection.updateOne(
  {},//filter
  { //update object
    <update operator>: {<field1>:<value1>, ...},
    <update operator>: {<field2>:<value2>, ...}
  },
  {} //options
)

db.collection.updateMany(
  {},//filter
  { //update object
    <update operator>: {<field1>:<value1>, ...},
    <update operator>: {<field2>:<value2>, ...}
  },
  {} //options
)

db.collection.replaceOne(
  {},//filter
  { //update object
    <update operator>: {<field1>:<value1>, ...},
    <update operator>: {<field2>:<value2>, ...}
  },
  {} //options
)

其中,filter用来查询出需要更新的数据,update object定义了需要更新的字段和目标值。update object支持数据定义聚合管道来更新数据。options, 定义upsert, writeconcern, collation, arrayFilter, hint等参数。

行为

原子性

Mongodb进行数据更新时,对单个文档的更新时原子性的。当使用updateMany方法更新多条数据时,updateMany操作不是原子性的,Mongodb会将updateMany中多条更新转换成逐条数据更新,而这种数据逐条更新操作,是原子性的。

_id字段

Mongodb中文档的_id字段是不可变的,不可以对_id字段进行更新。

字段顺序

写操作中,Mongodb默认保留文档插入式字段的顺序,但下面两种情况除外

  1. _id字段排在第一位
  2. 包含字段重新命名操作的数据更新,会触发字段顺序的重新排列。

Upsert选项

在操作updateOne(), updateMany(), replaceOne()方法中,指定upsert:true时,如果没有文档符合指定的过滤条件,数据更新操作会创建一个新的文档并插入到集合中。如果当前集合中有符合过滤条件的文档,则这些文档。

写入策略

Mongodb支持用户在options中自定义写入策略。

应用举例

构建测试集合

复制代码
db.inventory.insertMany([
   { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
   { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
])

更新{item:"paper"}的数据,即使可以找出多条文档, updateOne也只更新一条。默认按照数据插入时间排序。

复制代码
db.inventory.updateOne(
    { item: "paper"},
    {
        $set: {'size.uom': "cm", status: "p"},
        $currentDate: {lastModified: true}
    }
)

使用set,更新字段'size.uom'和字段status的值。同时,使用currentDate,将lastModified字段更新到当前时间。如果字段lastModified不存在,则添加该字段。

更新多个文档数据

复制代码
db.inventory.updateMany(
    {"qty": { $lt: 50}},
    {
        $set: {"size.uom": "in", status: "p"},
        $currentDate: {lastModified: true}
    }
)

替换一个文档

复制代码
db.inventory.replaceOne(
    { item: "paper"},
    { item: "paper", instock:[{warehouse: "A", qty: 60}, {warehouse: "B", qty: 40}]}
    )

Mongodb支持替换文档中除了_id字段外的所有字段。更新后的文档字段,可以与源文档的字段不同。使用replaceOne时,用来替换的新文档中,必须由键值对构成,不可以包含update操作符和表达式。

相关推荐
code_whiter1 分钟前
01-MySQL数据库基础
数据库·mysql
weixin_3823952321 分钟前
本地部署 ERP 选型记录:从 Excel 到轻量系统的这几年
数据库·人工智能·数据挖掘
2401_891409261 小时前
期货量化用得上的几类行情数据:逐笔、Level2、分钟线和五档tick
数据库
海绵宝宝转agent1 小时前
基于Redis ZSet+AOP+注解实现限流注解算法
数据库·redis·算法
imDwAaY2 小时前
Redis 也能做消息队列?从 Stream 的存储讲到消费确认
数据库·redis·缓存
@Mike@2 小时前
13-数据库学习笔记(查询执行处理模型)
数据库·笔记·学习
弈栈录2 小时前
MySQL 事务、索引与锁:后端开发必须掌握的数据库基础
数据库·后端
9624562 小时前
餐饮 SaaS 优惠券系统架构演进(三):优惠计算引擎——商品级计价、冲突策略与优惠分摊
java·数据库·spring boot
染指11102 小时前
135.Agent-多Agent框架-LangChain多智能体(SubAgents子代理)
数据库·人工智能·设计模式·langchain·agent·agents
Elastic 中国社区官方博客3 小时前
错误最多的服务运行正常:使用 ES|QL 从日志进行根因分析
大数据·运维·数据库·sql·elasticsearch·搜索引擎·全文检索