MongoDB-CN-Manual
  • MongoDB中文手册|官方文档中文版
  • MongoDB用户手册说明
  • MongoDB简介
    • 入门
    • 数据库和集合
      • 视图
      • 按需物化视图
      • 封顶集合
      • 时间序列集合
    • 文档
    • BSON类型
      • Comparison and Sort Order
      • MongoDB Extended JSON (v2)
      • MongoDB Extended JSON (v1)
  • 安装 MongoDB
    • 安装MongoDB社区版
      • 在Linux上安装MongoDB社区版
      • 在macOS上安装MongoDB社区版
      • 在Windows上安装MongoDB社区版
    • 安装MongoDB企业版
      • 在Linux上安装MongoDB企业版
      • 在Mac OS安装MongoDB企业版
      • 在Windows安装MongoDB企业版
      • 使用Docker安装MongoDB企业版
    • 将社区版MongoDB升级到企业版MongoDB
    • 验证MongoDB软件包的完整性
  • The mongo Shell
    • 配置mongo Shell
    • 使用 mongo Shell帮助
    • 为mongo Shell编写脚本
    • mongo Shell中的数据类型
    • mongo Shell 快速参考
  • MongoDB CRUD操作
    • 插入文档
      • 插入方法
    • 查询文档
      • 在mongo Shell中迭代游标
      • 从查询返回的项目字段
      • 查询嵌入式文档数组
      • 查询数组
      • 查询空字段或缺少字段
      • 查询嵌入/嵌套文档
    • 更新文档
      • 更新方法
      • 聚合管道更新
    • 删除文档
      • 删除方法
    • 地理空间查询
      • 用地理空间查询查找餐馆
      • GeoJSON对象
    • 批量写入操作
    • 可重试写入
    • 可重试读取
    • SQL到MongoDB的映射图表
    • 文本搜索
      • 文本索引
      • 文本索引操作
      • 集合管道中的文本索引
      • 文本索引语言
    • Read Concern读关注
      • 读关注 "local"
      • 读关注 "available"
      • 读关注 "majority"
      • 读关注 "linearizable"
      • 读关注 "snapshot"
    • Write Concern写关注
    • MongoDB CRUD概念
      • 原子性和事务
      • 读隔离性,一致性和近因性
        • 因果一致性和读写关注
      • 分布式查询
      • 通过findAndModify进行线性化读取
      • 查询计划
      • 查询优化
        • 评估当前操作性能
        • 优化查询性能
        • 写操作性能
        • 说明结果
      • 分析查询表现
      • Tailable 游标
  • MongoDB聚合
    • 聚合管道
      • 聚合管道优化
      • 聚合管道限制
      • 聚合管道和分片集合
      • 使用 Zip Code 数据集进行聚合
      • 使用用户首选项数据进行聚合
    • Map-Reduce
      • Map-Reduce 和分片集合
      • Map-Reduce 并发
      • Map-Reduce 示例
      • 执行增量 Map-Reduce
      • 对 Map Function 进行故障排除
      • 排除 Reduce Function 问题
      • Map-Reduce转换到聚合管道
    • 聚合参考
      • 聚合管道快速参考
      • 聚合命令
      • 聚合命令对比
      • 聚合表达式中的变量
      • SQL 到聚合映射图表
  • MongoDB数据模型
    • 数据建模介绍
    • 模式验证
    • 数据模型设计
      • 一对一嵌套关系模型
  • MongoDB事务
  • MongoDB事务
    • 驱动程序 API
    • 生产注意事项
    • 生产注意事项 (分片集群)
    • 事务操作
  • MongoDB索引
    • 单字段索引
    • 复合索引
    • 多键索引
      • 多键索引范围
    • 文本索引
      • 为文本索引指定语言
      • 指定文本索引的名称
      • 用权重控制搜索结果
      • 限制扫描条目的数量
    • 通配符索引
      • 通配符索引限制
    • 2dsphere 索引
      • 查询一个2dsphere索引
    • 2d 索引
      • 创建一个2d索引
      • 查询一个2d索引
      • 2d索引内部
      • 使用球面几何计算距离
    • geoHaystack 索引
      • 创建Haystack索引
      • 查询Haystack索引
    • 哈希索引
    • 索引特性
      • TTL 索引
        • 通过设置TTL使集合中的数据过期
      • 唯一索引
      • 部分索引
      • 不分大小写索引
      • Sparse 索引
    • 在填充的集合上建立索引
      • 在副本集上建立滚动索引
      • 在分片群集上建立滚动索引
    • 索引交集
    • 管理索引
    • 衡量索引使用
    • 索引策略
      • 创建索引来支持查询
      • 使用索引对查询结果进行排序
      • 确保索引适合RAM
      • 创建以确保选择性的查询
    • 索引参考
  • MongoDB安全
    • 安全检查列表
    • 启用访问控制
    • 身份验证
      • 用户
        • 添加用户
        • 权限认证机制
          • SCRAM
            • 用x.509证书来认证客户端
    • 审计
      • 配置审计过滤器
      • 配置审计
      • 系统事件审计消息
    • 网络和配置强化
    • 安全参考
      • system.roles集合
      • system.users集合
      • 资源文档
      • 权限操作
    • 附录
      • 附录-A-用于测试的 OpenSSl CA 证书
      • 附录-B-用于测试的OpenSSL服务器证书
      • 附录-C-用于测试的OpenSSL客户端证书
  • Change Streams变更流
    • 变更流生产建议
    • 变更事件
  • MongoDB复制
    • 副本集成员
    • 副本集日志
    • 副本集数据同步
    • 副本集部署架构
    • 副本集成员配置教程
    • 副本集维护教程
    • MongoDB复制参考
  • MongoDB分片
    • 分片集群组件
    • 分片键
    • 哈希分片
    • 范围分片
    • 区
      • 管理分片区
      • 按位置细分数据
      • 用于更改SLA或SLO的分层硬件
      • 按应用或客户细分数据
      • 仅插入工作负载的分布式本地写入
      • 管理分片区
    • 使用块进行数据分区
      • 在分片集群中拆分数据块
    • 分片管理
      • 查看集群设置
    • 重启一个分片集群
    • [把一个分片集群迁移到不同的硬件](fen-pian/migrate-a -sharded-cluster-to-different-hardware.md)
    • 分片参考
  • MongoDB管理
    • 产品说明
    • 操作检查列表
    • 开发检查列表
    • 配置和维护
    • 性能
    • 数据中心意识
      • MongoDB部署中的工作负载隔离
      • 区
        • 管理分片区
        • 按位置细分数据
        • 用于更改SLA或SLO的分层硬件
        • 按应用或客户细分数据
        • 仅插入工作负载的分布式本地写入
        • 管理分片区
    • MongoDB备份方法
    • MongoDB监控
  • MongoDB存储
    • 存储引擎
      • WiredTiger 存储引擎
      • 内存存储引擎
    • 日志记录
      • 管理日志记录
        • GridFS
        • FAQ:MongoDB 存储
  • MongoDB参考
    • 运算符
      • 查询与映射运算符
        • 比较查询运算符
          • $eq
          • $gt
          • $gte
          • $in
          • $lt
          • $lte
          • $ne
          • $nin
        • 逻辑查询运算符
          • $and
          • $not
          • $nor
          • $or
        • 元素查询运算符
        • 评估查询运算符
        • 地理空间查询运算符
        • 数组查询运算符
        • 按位查询运算符
        • $comment
        • 映射运算符
      • 更新运算符
        • 字段更新运算符
        • 数组更新运算符
        • 按位更新运算符
      • 聚合管道阶段
      • 聚合管道操作符
        • $abs (aggregation)
        • $acos (aggregation)
        • $acosh (aggregation)
        • $add (aggregation)
        • $addToSet (aggregation)
        • $allElementsTrue (aggregation)
        • $and (aggregation)
        • $anyElementTrue (aggregation)
        • $arrayElemAt (aggregation)
        • $arrayToObject (aggregation)
        • $asin (aggregation)
        • $asinh (aggregation)
        • $atan (aggregation)
        • $atan2 (aggregation)
        • $atanh (aggregation)
        • $avg (aggregation)
        • $ceil (aggregation)
        • $cmp (aggregation)
        • $concat (aggregation)
        • $concatArrays (aggregation)
        • $cond (aggregation)
        • $convert (aggregation)
        • $cos (aggregation)
        • $dateFromParts (aggregation)
        • $dateToParts (aggregation)
        • $dateFromString (aggregation)
        • $literal (aggregation)
      • 查询修饰符
    • 数据库命令
      • 聚合命令
      • 地理空间命令
      • 查询和写操作命令
      • 查询计划缓存命令
      • 认证命令
      • 用户管理命令
      • 角色管理命令
      • 复制命令
      • 分片命令
      • 会话命令
      • 管理命令
      • 诊断命令
      • 免费监控命令
      • 系统事件审计命令
    • mongo Shell 方法
      • 集合方法
        • db.collection.aggregate()
        • db.collection.bulkWrite()
        • db.collection.copyTo()
        • db.collection.count()
        • db.collection.countDocuments()
        • db.collection.estimatedDocumentCount()
        • db.collection.createIndex()
        • db.collection.createIndexes()
        • db.collection.dataSize()
        • db.collection.deleteOne()
        • db.collection.deleteMany()
        • db.collection.distinct()
        • db.collection.drop()
        • db.collection.dropIndex()
        • db.collection.dropIndexes()
        • db.collection.ensureIndex()
        • db.collection.explain()
        • db.collection.find()
        • db.collection.findAndModify()
        • db.collection.findOne()
        • db.collection.findOneAndDelete()
        • db.collection.findOneAndReplace()
        • db.collection.findOneAndUpdate()
        • db.collection.getIndexes()
        • db.collection.getShardDistribution()
        • db.collection.getShardVersion()
        • db.collection.insert()
        • db.collection.insertOne()
        • db.collection.insertMany()
        • db.collection.isCapped()
        • db.collection.latencyStats()
        • db.collection.mapReduce()
        • db.collection.reIndex()
        • db.collection.remove()
        • db.collection.renameCollection()
        • db.collection.replaceOne()
        • db.collection.save()
        • db.collection.stats()
        • db.collection.storageSize()
        • db.collection.totalIndexSize()
        • db.collection.totalSize()
        • db.collection.update()
        • db.collection.updateOne()
        • db.collection.updateMany()
        • db.collection.watch()
        • db.collection.validate()
    • MongoDB中的限制与阈值
    • MongoDB系统集合
    • 词汇表
    • 默认的MongoDB端口
    • 默认的MongoDB读/写关注
    • 服务器会话
  • MongoDB FAQ
    • FAQ: MongoDB基础知识
    • FAQ: MongoDB索引
    • FAQ: MongoDB并发
    • FAQ: MongoDB分片
    • FAQ: MongoDB复制和副本集
    • FAQ: MongoDB存储
    • FAQ: MongoDB诊断
  • MongoDB 版本管理
  • 联系我们
    • Tapdata Cloud
    • MongoDB中文社区
    • 社区合作伙伴—锦木信息
由 GitBook 提供支持
在本页
  • 定义
  • 行为
  • 投影
  • 分片集合
  • 事务
  • 例子
  • 替换文档
  • 排序和替换文档
  • 投射退回文件
  • 用 Time Limit 替换 Document
  • 用 Upsert 替换文档
  • 指定排序规则
  1. MongoDB参考
  2. mongo Shell 方法
  3. 集合方法

db.collection.findOneAndReplace()

上一页db.collection.findOneAndDelete()下一页db.collection.findOneAndUpdate()

最后更新于3年前

在本页面

定义

  • db.collection. findOneAndReplace(过滤,替换,选项)

    • version 3.2 中的新内容。

根据filter和sort条件修改和替换单个文档。

findOneAndReplace()方法具有以下形式:

db.collection.findOneAndReplace(
    <filter>,
    <replacement>,
    {
        projection: <document>,
        sort: <document>,
        maxTimeMS: <number>,
        upsert: <boolean>,
        returnNewDocument: <boolean>,
        collation: <document>
    }
)

findOneAndReplace()方法采用以下参数:

参数
类型
描述

filter

document

更新的选择标准。可以使用与find()方法相同的query selectors。 指定一个空文档{ }以替换集合中返回的第一个文档。 如果未指定,则默认为空文档。 从 MongoDB 3.6.14(和 3.4.23)开始,如果查询参数不是文档,则操作错误。

replacement

document

替换文件。 不能包含更新 operators。 <replacement>文档无法指定与替换文档不同的_id value。

projection

document

可选的。 return 的字段子集。 要_return 匹配文档中的所有字段,请省略此参数。 从 MongoDB 3.6.14(和 3.4.23)开始,如果投影参数不是文档,则操作错误。

sort

document

可选的。为filter匹配的文档指定排序 order。 从 MongoDB 3.6.14(和 3.4.23)开始,如果 sort 参数不是文档,则操作错误。 见cursor.sort()。

maxTimeMS

number

可选的。指定操作必须在其中完成的 time 限制(以毫秒为单位)。如果超出限制则引发错误。

upsert

boolean

可选的。当true,findOneAndReplace()时: 如果没有文档与filter匹配,则从replacement参数插入文档。插入新文档后返回null,除非returnNewDocument是true。 用replacement文档替换与filter匹配的文档。 MongoDB 将_id字段添加到替换文档中,如果未在filter或replacement文档中指定。如果两者都存在_id,则值必须相等。 要避免多次 upsert,请确保query字段为唯一索引。 默认为false。

returnNewDocument

boolean

可选的。当true时,返回替换文档而不是原始文档。 默认为false。

collation

document

可选的。 指定要用于操作的整理。 整理允许用户为 string 比较指定 language-specific 规则,例如字母和重音标记的规则。 排序规则选项具有以下语法: 排序规则:{ locale:<string>, caseLevel:<boolean>, caseFirst:<string>, strength:<int>, numericOrdering:<boolean>, alternate:<string>, maxVariable:<string>, backwards :<boolean> } 指定排序规则时,locale字段是必填字段;所有其他校对字段都是可选的。有关字段的说明,请参阅整理文件。 如果未指定排序规则但集合具有默认排序规则(请参阅db.createCollection()),则操作将使用为集合指定的排序规则。 如果没有为集合或操作指定排序规则,MongoDB 使用先前版本中用于 string 比较的简单二进制比较。 您无法为操作指定多个排序规则。对于 example,您不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一个排序规则,而对排序使用另一个排序规则。 version 3.4 中的新内容。

返回:

返回原始文档,如果是returnNewDocument: true,则返回替换文档。

行为

findOneAndReplace()替换集合中与filter匹配的第一个匹配文档。 sort参数可用于影响修改哪个文档。

投影

projection参数采用以下形式的文档:

{ field1 : < boolean >, field2 : < boolean > ... }

<boolean> value 可以是以下任何一种:

  • 1或true包括该字段。即使未在投影参数中明确说明,该方法也会返回_id字段。

  • 0或false排除该字段。这可以在任何字段上使用,包括_id。

分片集合

要db.collection.findOneAndReplace()在分片集合上使用,查询过滤器必须在分片键上包含相等条件。

碎片键修改

从MongoDB 4.2开始,您可以更新文档的分片键值,除非分片键字段是不可变_id字段。有关更新分片键的详细信息,请参见更改文档的分片键值。

在MongoDB 4.2之前,文档的分片键字段值是不可变的。

事务

db.collection.findOneAndReplace()可以在多文档交易中使用。

如果该操作导致upsert,则该集合必须已经存在。

如果在事务中运行,请不要为操作明确设置写关注点。要对事务使用写关注,请参见 事务和写关注。

重要

在大多数情况下,与单文档写入相比,多文档事务产生的性能成本更高,并且多文档事务的可用性不应替代有效的架构设计。在许多情况下, 非规范化数据模型(嵌入式文档和数组)将继续是您的数据和用例的最佳选择。也就是说,在许多情况下,适当地对数据建模将最大程度地减少对多文档交易的需求。

有关其他事务使用方面的注意事项(例如运行时限制和操作日志大小限制),另请参见 生产注意事项。

例子

替换文档

scores集合包含类似于以下内容的文档:

{ "_id" : 1521, "team" : "Fearful Mallards", "score" : 25000 },
{ "_id" : 2231, "team" : "Tactful Mooses", "score" : 23500 },
{ "_id" : 4511, "team" : "Aquatic Ponies", "score" : 19250 },
{ "_id" : 5331, "team" : "Cuddly Zebras", "score" : 15235 },
{ "_id" : 3412, "team" : "Garrulous Bears", "score" : 22300 }

以下操作查找score小于20000的第一个文档并替换它:

db.scores.findOneAndReplace(
    { "score" : { $lt : 20000 } },
    { "team" : "Observant Badgers", "score" : 20000 }
)

该操作返回已替换的原始文档:

{ "_id" : 2512, "team" : "Aquatic Ponies", "score" : 19250 }

如果returnNewDocument是 true,则操作将_return 替换文档。

排序和替换文档

scores集合包含类似于以下内容的文档:

{ "_id" : 1521, "team" : "Fearful Mallards", "score" : 25000 },
{ "_id" : 2231, "team" : "Tactful Mooses", "score" : 23500 },
{ "_id" : 4511, "team" : "Aquatic Ponies", "score" : 19250 },
{ "_id" : 5331, "team" : "Cuddly Zebras", "score" : 15235 },
{ "_id" : 3412, "team" : "Garrulous Bears", "score" : 22300 }

按score排序会更改操作的结果。以下操作按score升序对filter的结果进行排序,并替换最低得分文档:

db.scores.findOneAndReplace(
    { "score" : { $lt : 20000 } },
    { "team" : "Observant Badgers", "score" : 20000 },
    { sort: { "score" : 1 } }
)

该操作返回已替换的原始文档:

{ "_id" : 5112, "team" : "Cuddly Zebras", "score" : 15235 }

有关此命令的 non-sorted 结果,请参见替换文档。

投射退回文件

scores集合包含类似于以下内容的文档:

{ "_id" : 1521, "team" : "Fearful Mallards", "score" : 25000 },
{ "_id" : 2231, "team" : "Tactful Mooses", "score" : 23500 },
{ "_id" : 4511, "team" : "Aquatic Ponies", "score" : 19250 },
{ "_id" : 5331, "team" : "Cuddly Zebras", "score" : 15235 },
{ "_id" : 3412, "team" : "Garrulous Bears", "score" : 22300 }

以下操作使用 projection 仅显示返回文档中的team字段:

db.scores.findOneAndReplace(
    { "score" : { $lt : 22250 } },
    { "team" : "Therapeutic Hamsters", "score" : 22250 },
    { sort : { "score" : 1 }, project: { "_id" : 0, "team" : 1 } }
)

该操作返回仅包含team字段的原始文档:

{ "team" : "Aquatic Ponies"}

用 Time Limit 替换 Document

以下操作设置完成的 5ms time 限制:

try {
    db.scores.findOneAndReplace(
        { "score" : { $gt : 25000 } },
        { "team" : "Emphatic Rhinos", "score" : 25010 },
        { maxTimeMS: 5 }
    );
} catch(e){
    print(e);
}

如果操作超过 time 限制,则返回:

Error: findAndModifyFailed failed: { "ok" : 0, "errmsg" : "operation exceeded time limit", "code" : 50 }

用 Upsert 替换文档

如果没有匹配的filter,则以下操作使用upsert字段来插入替换文档:

try {
    db.scores.findOneAndReplace(
        { "team" : "Fortified Lobsters" },
        { "_id" : 6019, "team" : "Fortified Lobsters" , "score" : 32000},
        { upsert : true, returnNewDocument: true }
    );
} catch (e){
    print(e);
}

该操作返回以下内容:

{
    "_id" : 6019,
    "team" : "Fortified Lobsters",
    "score" : 32000
}

如果returnNewDocument是 false,则操作将返回null,因为 return 没有原始文档。

指定排序规则

version 3.4 中的新内容。

整理允许用户为 string 比较指定 language-specific 规则,例如字母和重音标记的规则。

集合myColl具有以下文档:

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

以下操作包括整理选项:

db.myColl.findOneAndReplace(
    { category: "cafe", status: "a" },
    { category: "cafÉ", status: "Replaced" },
    { collation: { locale: "fr", strength: 1 } }
);

该操作返回以下文档:

{ "_id" : 1, "category" : "café", "status" : "A" }

译者:李冠飞

校对:

定义
行为
例子