文档菜单
文档首页
/ / /
Ruby MongoDB 驱动程序
/

CRUD 操作

本页内容

  • 键值对表示法
  • 创建文档
  • 查询缓存
  • 读取
  • 更新
  • 删除
  • 写入关注
  • 带点/句号 (.) 和美元符号 ($) 的字段名称
  • 关于 BSON 符号类型的说明

CRUD 操作是指处理创建、读取、更新和删除文档的操作。

键值对在MongoDB Ruby驱动程序中的许多不同上下文中出现,并且它们的表示法有一些语法上的怪癖,这取决于你使用的Ruby版本。

当构建文档时,以下语法对于Ruby 1.9及以后的版本是可接受和正确的。

document = { name: "Harriet", age: 36 }

如果你使用的是Ruby 2.2或更高版本,你可以选择将键用引号括起来。

document = { "name": "Harriet", "age": 36 }

如果你需要使用以$开头的任何MongoDB运算符,例如$set$gte$near,你必须将其用引号括起来。如果你使用的是Ruby 2.2或更高版本,你可以这样表示:

collection.update_one({ name: "Harriet" }, { "$set": { age: 42 } })

如果你使用的是早期版本的Ruby,请使用hashrocket符号

collection.update_one({ name: "Harriet" }, { "$set" => { age: 42 } })

引号字符串和hashrockets对键值对将适用于任何版本的Ruby

collection.update_one({ "name" => "Harriet" }, { "$set" => { age: 42 } })

要将文档插入到集合中,请在客户端选择一个集合,并调用insert_oneinsert_many

插入操作返回一个Mongo::Operation::Result对象,它提供了有关插入本身的信息。

在MongoDB 2.6及以后的版本中,如果插入失败,将引发异常,因为使用了写命令。

在MongoDB 2.4中,只有在插入失败且写关注为1或更高时,才会引发异常。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
result = client[:artists].insert_one( { :name => 'FKA Twigs' } )
result.n # returns 1, because 1 document was inserted.
result = client[:artists].insert_many([
{ :name => 'Flying Lotus' },
{ :name => 'Aphex Twin' }
])
result.inserted_count # returns 2, because 2 documents were inserted.

版本中3.4.

Decimal128 是一种BSON 数据类型,它使用基于 128 位十进制的浮点值,能够以精确的精度模拟十进制舍入。此功能适用于处理 货币数据 的应用程序,例如金融和税务计算。

以下示例将一个 Decimal128 类型的值插入名为 inventory 的集合中的 price 字段

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
price = BSON::Decimal128.new("428.79")
client[:inventory].insert_one({ "_id" => 1,
"item" => "26 inch monitor",
"price" => price })

上述操作生成以下文档

{ "_id" : 1, "item" : "26 inch monitor", "price" : NumberDecimal("428.79") }

您还可以从 Ruby 的 BigDecimal 对象创建一个 Decimal128 对象,或者使用 Decimal128.from_string()

big_decimal = BigDecimal.new(428.79, 5)
price = BSON::Decimal128.new(big_decimal)
# => BSON::Decimal128('428.79')
price = BSON::Decimal128.from_string("428.79")
# => BSON::Decimal128('428.79')

Ruby 驱动程序提供了一个查询缓存。当启用时,查询缓存将保存查找和聚合查询的结果,并在再次执行相同的查询时返回这些保存的结果。

要了解更多关于查询缓存的信息,请访问 查询缓存教程。

Ruby 驱动为集合上的 find 方法提供了流畅的查询接口。为 find 方法提供了各种选项。

查询仅在迭代结果时才对服务器进行懒加载执行 - 在这一点上,查询会被发送,并返回一个 Mongo::Cursor

要查找给定过滤器下的所有文档,请使用查询调用 find

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').each do |document|
#=> Yields a BSON::Document.
end

要查询嵌套文档,请使用点符号指定嵌套顺序的键。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find("records.releaseYear": 2008).each do |document|
#=> Yields a BSON::Document.
end

此用法已弃用。

使用遗留的 $query 语法,find 方法允许在第一个参数中提供查询和选项。

collection.find(:'$query' => {name: 'Mr. Smith'})
# Equivalent to:
collection.find(name: 'Mr. Smith')
collection.find(:'$query' => {name: 'Mr. Smith'}, :'$sort' => {age: 1})
# Equivalent to:
collection.find(name: 'Mr. Smith').sort(age: 1)

当查询针对 MongoDB 3.2 或更高版本执行时,驱动程序将使用针对所涉及的服务器版本的适当协议,并自动将查询转换为 find 命令或 OP_MSG 负载。

要将选项添加到查询中,请在 find 方法之后链式调用适当的函数。请注意,底层对象 Mongo::Collection::View 是不可变的,并且在每次方法调用后都会返回一个新的对象。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
documents = client[:artists].find(:name => 'Flying Lotus').skip(10).limit(10)
documents.each do |document|
#=> Yields a BSON::Document.
end

以下是可在查询时添加的选项的完整列表及其对应的示例方法。

选项
描述
allow_disk_use
当设置为 true 时,服务器可以在执行 find 操作时将临时数据写入磁盘。此选项仅在 MongoDB 服务器版本 4.4 及更高版本上可用。
allow_partial_results
用于分片集群。如果某个分片失效,允许查询从处于正常运行状态的分片返回结果,可能只能得到部分结果。
batch_size(Integer)
指定游标在每次 GETMORE 操作中返回的文档批次的尺寸。
comment(String)
向查询添加注释。
explain(**opts)

返回查询的查询计划。通过使用符号键作为关键字参数传递explain 选项

# All server versions - default explain behavior
client[:artists].find.explain
# MongoDB 3.0 and newer
client[:artists].find.explain(verbosity: :query_planner)
client[:artists].find.explain(verbosity: :execution_stats)
client[:artists].find.explain(verbosity: :all_plans_execution)
# Alternative syntax using camel case
client[:artists].find.explain(verbosity: "queryPlanner")
client[:artists].find.explain(verbosity: "executionStats")
client[:artists].find.explain(verbosity: "allPlansExecution")
# MongoDB 2.6
client[:artists].find.explain(verbose: true)

explain 操作支持 :session:read(用于读取偏好)选项。为了为单个 explain 操作指定这些选项,必须按照以下方式将它们提供给 find 方法:

client[:artists].find({}, session: session).explain
client[:artists].find({}, read: {mode: :secondary_preferred}).explain

如果读取偏好选项在客户端或集合上指定,它将被传递给 explain 操作。

client[:artists, read: {mode: :secondary_preferred}].find.explain

请注意,在创建集合对象时,不接受会话选项。

explain 命令不支持传递读取关注选项。如果读取关注在客户端或集合级别指定,或者如果读取关注作为 find 选项指定,它将不会被驱动程序传递给 explain 命令。

服务器为 explain 命令返回的信息因服务器版本和部署拓扑而异。驱动程序的 explain 方法返回服务器提供的任何信息。

explain 方法的返回值不是驱动程序公共 API 的一部分,并且取决于服务器版本和部署拓扑。

hint(Hash)
为查询提供索引提示以使用。
let(Hash)
变量映射到查询中使用的映射。
limit(Integer)
限制返回的文档数到提供的值。
max_scan(Integer)
如果执行完整集合扫描,则设置要扫描的最大文档数。自 MongoDB 服务器版本 4.0 起已弃用。
max_time_ms(Integer)
允许查询运行的最大时间,以毫秒为单位。
no_cursor_timeout
MongoDB 在 10 分钟后自动关闭不活动的游标。调用此方法以使游标在服务器上无限期保持打开状态。
projection(Hash)

指定要包含或排除的结果字段。

client[:artists].find.projection(:name => 1)
read(Hash)

仅更改此查询的读取偏好。

client[:artists].find.read(:mode => :secondary_preferred)
session(Session)
要使用的会话。
show_disk_loc(Boolean)
告诉结果还包括文档在磁盘上的位置。
skip(Integer)
在结果中跳过提供的文档数。
snapshot
以快照模式执行查询。自 MongoDB 服务器版本 4.0 起已弃用。
sort(Hash)

指定查询的排序标准。

client[:artists].find.sort(:name => -1)
count_documents
获取匹配过滤器或集合中所有文档的总数。
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').count_documents
estimated_document_count

获取集合中文档的大致数量。

请注意,与count_documents不同,estimated_document_count不接受过滤器。

使用count服务器命令来实现estimated_document_count。更多信息可以通过计数:行为获取。

由于MongoDB版本5.0.0-5.0.7中的一个疏忽,count命令(estimated_document_count在其实现中使用的命令)未包含在稳定API的v1中。因此,使用estimated_document_count的稳定API用户建议将服务器版本升级到5.0.8+或设置api_strict: false以避免遇到错误。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].estimated_document_count
count

获取匹配过滤器文档的大致数量,或获取集合中文档的大致数量。

已弃用: count方法已弃用,不支持在事务中使用。请使用count_documents来获取可能匹配的文档的确切数量,或使用estimated_document_count来获取集合中文档的大致数量。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').count
distinct
过滤掉具有重复值的文档。等同于SQL中的distinct子句。
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find.distinct(:name )

对于受限集合,您可以使用在客户端耗尽初始游标结果后仍然保持打开的可 tail 追踪游标。以下代码示例显示了如何使用可 tail 追踪游标:

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].drop
client[:artists, capped: true, size: 512].create
result = client[:artists].insert_many([
{ :name => 'Flying Lotus' },
{ :name => 'Aphex Twin' }
])
enum = client[:artists].find({}, cursor_type: :tailable_await).to_enum
while true
doc = enum.next
# do something
sleep(1)
end

读取关注可以在客户端或集合上设置

client = Mongo::Client.new(['localhost:14420'], database: 'music',
read_concern: {level: :local})
client['collection'].find.to_a
collection = client['collection', read_concern: {level: :majority}]
collection.find.to_a

当前驱动程序不支持在单个查询上设置读取关注。

在开始事务时可以指定读取关注度。开始事务时,当事务处于活动状态时,客户端或集合上指定的任何读取关注度都被忽略。

当使用通用命令助手时,读取关注度可以作为命令的一部分指定

client.database.command(dbStats: 1, readConcern: {level: :majority})

读取偏好确定可以发送查询或命令的候选 副本集成员。它们包括一个指定为符号的 模式,一个称为 tag_sets 的哈希数组,一个 hedge 选项,这是一个指定保险丝读取行为的哈希,以及两个时间选项:local_thresholdserver_selection_timeout

local_threshold
定义了最近的服务器与可能发送操作的服务器之间延迟窗口的上限(以秒为单位)。默认值为15毫秒,即0.015秒。
server_selection_timeout
定义了在抛出异常之前用于服务器选择的阻塞时间。默认值为30,000毫秒,即30秒。

注意

读取偏好不适用于独立部署。当客户端连接到独立部署时,任何由应用程序指定的读取偏好都将被忽略。

有关选择服务器的算法的更多信息,请参阅GitHub上的服务器选择文档

读取偏好可以在客户端设置,或在数据库上运行命令时传递选项。

# Set read preference on a client, used for all operations
client = Mongo::Client.new([ '127.0.0.1:27017' ],
read: { mode: :secondary,
tag_sets: [ { 'dc' => 'nyc' } ]
} )
# Set read preference for a given command
client.database.command( { dbStats: 1 }, read: { mode: secondary,
tag_sets: [ { 'dc' => 'nyc' } ] } )

还可以使用with方法为集合上的特定操作设置读取偏好。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.with(:read => { :mode => :primary_preferred }).find.to_a

有五种可能的读取偏好模式::primary:secondary:primary_preferred:secondary_preferred:nearest。请参阅MongoDB手册中的读取偏好文档了解这些模式的说明。

注意

当客户端直接使用:direct_connection Ruby选项或directConnection URI选项连接到服务器时,读取偏好模式自动设置为:primary_preferred,允许对次级进行读取操作。如果应用程序指定了:primary读取偏好模式,则模式自动转换为:primary_preferred。如果指定了其他读取偏好模式,则它将不变地传递给服务器。

参数 tag_sets 是一个有序的标签集列表,用于限制选择服务器的资格,例如数据中心感知。请参阅MongoDB手册中的读写偏好文档以了解标签集的说明。

如果 T 是 S 的子集,则读写偏好标签集(T)与服务器标签集(S)匹配,或者等价地,服务器标签集(S)与读写偏好标签集(T)匹配。

例如,读写偏好标签集 { dc: 'ny', rack: 2 } 与标签集为 { dc: 'ny', rack: 2, size: 'large' } 的辅助服务器匹配。

一个空文档的标签集与任何服务器匹配,因为空标签集是任何标签集的子集。这意味着默认的 tag_sets 参数 [{}] 与所有服务器匹配。

hedge 参数是一个哈希,用于指定服务器是否应使用规避读取。在规避读取的情况下,分片集群可以将读取操作路由到两个副本集成员,并返回第一个响应者的结果。

hedge 选项仅适用于非主读写偏好。它必须作为一个键为 enabled 并设置为 truefalse 的哈希提供。

client = Mongo::Client.new(
[ '127.0.0.1:27017' ],
read: { mode: :secondary, hedge: { enabled: true } },
)

请参阅MongoDB手册以了解有关规避读取的更多信息。

注意

hedge 选项仅在MongoDB服务器版本4.4及更高版本中可用。在较旧的服务器版本上尝试使用此选项将导致错误。

可以通过执行单个或多个更新,或使用 $findAndModify 命令来更新文档。

update_one

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
result = artists.find(:name => 'Goldie').update_one("$inc" => { :plays => 1 } )
result.n # Returns 1.
result = artists.update_one( { :name => 'Goldie' }, { "$inc" => { :plays => 1 } } )
result.n # Returns 1.

update_many

result = artists.find(:label => 'Hospital').update_many( "$inc" => { :plays => 1 } )
result.modified_count # Returns the number of documents that were updated.
result = artists.update_many( { :label => 'Hospital' }, { "$inc" => { :plays => 1 } } )
result.modified_count # Returns the number of documents that were updated.

replace_one

result = artists.find(:name => 'Aphex Twin').replace_one(:name => 'Richard James')
result.modified_count # Returns 1.
result = artists.replace_one( { :name => 'Aphex Twin' }, { :name => 'Richard James' } )
result.modified_count # Returns 1.

要更新文档并通过 $findAndModify 返回文档,请使用以下三个提供的辅助函数之一:find_one_and_deletefind_one_and_replacefind_one_and_update。您可以选择在修改发生之前或之后返回文档。

find_one_and_delete

client = Mongo::Client.new( [ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.find(:name => 'José James').find_one_and_delete # Returns the document.

find_one_and_replace

doc = artists.find(:name => 'José James').find_one_and_replace(:name => 'José')
doc # Return the document before the update.
doc = artists.find_one_and_replace({ :name => 'José James' }, { :name => 'José' })
doc # Return the document before the update.
doc = artists.find(:name => 'José James').
find_one_and_replace( { :name => 'José' }, :return_document => :after )
doc # Return the document after the update.

find_one_and_update

doc = artists.find(:name => 'José James').
find_one_and_update( '$set' => { :name => 'José' } )
doc # Return the document before the update.
doc = artists.find_one_and_update( { :name => 'José James' }, { '$set' => { :name => 'José' } } )
doc # Return the document before the update.

要向更新命令添加选项,请将它们指定为选项哈希参数中的键值对。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.indexes.create_one(name: 1)
# Force the server to use the name index to perform this operation
result = artists.update_one(
{ :name => 'Goldie' },
{ "$inc" => { :plays => 1 } },
{ hint: { name: 1 } }
)
result.n # Returns 1.

以下是可以添加到更新操作(包括 update_oneupdate_manyreplace_onefind_one_and_deletefind_one_and_updatefind_one_and_replace)中的选项列表。

选项
描述
array_filters
一个过滤器文档数组,用于确定更新操作中要修改的数组字段的元素。
bypass_document_validation
是否在写入文档之前跳过文档级验证。
collation
指定用于比较字符串的一组规则,这些字符串符合特定语言的约定。
hint
指定此操作要使用的索引。可以是哈希(例如 { _id: 1 })或字符串(例如 "_id_")。在 MongoDB 服务器版本 4.2 及以上支持 update_oneupdate_manyreplace_one 命令,在服务器版本 4.4 及以上支持 find_one_and_deletefind_one_and_updatefind_one_and_replace 命令。
let(Hash)
将变量映射到要在此操作中使用的操作。
projection
在操作结果中排除或包含的字段(仅在 find_one_and_deletefind_one_and_replacefind_one_and_update 命令中可用)。
return_document
指定是否返回更新前或更新后的更新文档。可能的值是 :before:after。(仅在 find_one_and_updatefind_one_and_replace 命令中可用)。
sort
如何对find和modify命令的结果进行排序。指定为一个键值对,其中键是要排序的字段名称,值是1或-1,指定升序或降序排序(仅在find_one_and_deletefind_one_and_replacefind_one_and_update命令中使用)。
会话
用于此操作的会话。
upsert
如果文档不存在,是否执行upsert。不能用于find_one_and_delete操作。

有关更新选项的更多信息,请参阅以下命令的MongoDB服务器文档

  • 更新

  • findAndModify

delete_one

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
result = artists.find(:name => 'Björk').delete_one
result.deleted_count # Returns 1.
result = artists.delete_one(:name => 'Björk')
result.deleted_count # Returns 1.

delete_many

result = artists.find(:label => 'Mute').delete_many
result.deleted_count # Returns the number deleted.
result = artists.delete_many(:label => 'Mute')
result.deleted_count # Returns the number deleted.

要将选项添加到删除命令中,请将它们指定为选项哈希参数中的键值对。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.indexes.create_one(name: 1)
# Force the server to use the name index to perform this operation
result = artists.find(:name => 'Björk').delete_one(hint: { name: 1 })
result.deleted_count # Returns 1.

以下是可以添加到delete_onedelete_many操作中的所有可用选项的完整列表。

选项
描述
collation
指定用于比较字符串的一组规则,这些字符串符合特定语言的约定。
hint
用于此操作的要使用的索引。可以是哈希(例如{ _id: 1 })或字符串(例如"_id_")。支持MongoDB服务器版本4.4及以上。
let(Hash)
用于此操作的变量映射。
会话
用于此操作的会话。

有关更新选项的更多信息,请参阅删除命令。

在MongoDB中,所有写入操作都使用写入关注,这是MongoDB对特定写入请求的确认级别。有关写入关注的更多信息,请参阅MongoDB手册

Ruby驱动程序支持在客户端、集合、会话(该会话的事务)、事务、GridFS桶和写入流级别指定写入关注,以及在通过Database#command手动发出命令时。

从驱动程序版本2.10开始,所有接受写入关注的驱动程序对象都通过:write_concern选项进行,该选项应提供包含写入关注选项的哈希。现在已弃用:write选项的使用。在驱动程序版本2.9及以下版本中,客户端、集合和GridFS对象采用:write选项,而会话和事务对象则采用:write_concern选项。

以下是一些将写入关注传递给客户端和集合对象的示例。可以在构建新的客户端和集合对象时提供:write_concern选项,或者传递给#with方法。

有关GridFS的示例,请参阅GridFS页面。

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
alt_client = client.with(write_concern: {w: :majority})
collection = client[:artists, write_concern: {w: 3}]
alt_collection = collection.with(write_concern: {w: :majority})
# Uses w: 3
collection.insert_one({name: 'SUN Project'})
# Uses w: :majority
alt_collection.insert_one({name: 'SUN Project'})

驱动程序版本2.9及以下版本通过:write选项在客户端和集合级别接受写入关注。这种用法将继续为向后兼容性提供支持,但现在已弃用。

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write: {w: 2})
alt_client = client.with(write: {w: :majority})
collection = client[:artists, write: {w: 3}]
alt_collection = collection.with(write: {w: :majority})

如果同时提供了:write:write_concern选项,它们的值必须相同,否则将引发异常。

# OK
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 3}, write: {w: 3})
# Error
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 3}, write: {w: :majority})

当使用#with方法在客户端或集合上更改选项时,如果存在名称差异,则最后提供的选项获胜。

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
alt_client = client.with(write: {w: 3})
alt_client.options[:write]
# => {"w"=>3}
alt_client.options[:write_concern]
# => nil

在使用事务时,写关注只在执行commit_transactionabort_transaction操作时发送到服务器,具体请参照事务规范。可以通过在with_transactionstart_transaction调用中使用`:write_concern`选项,或者在会话对象的default_transaction_options选项中设置写关注。如果这些选项都没有设置,则使用客户端的写关注;注意,事务会忽略其操作涉及的集合的写关注。注意,当将写关注作为事务选项设置时,任何版本的驱动程序都不认可`:write`选项。

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
collection = client[:artists, write_concern: {w: :majority}]
session = client.start_session
session.with_transaction do
collection.insert_one({test: 1}, session: session)
# Uses w: 2 when committing
end
session = client.start_session(default_transaction_options:
{write_concern: {w: 3})
)
session.with_transaction do
collection.insert_one({test: 1}, session: session)
# Uses w: 3 when committing
end
session = client.start_session
session.with_transaction(write_concern: {w: 3}) do
collection.insert_one({test: 1}, session: session)
# Uses w: 3 when committing
end

当写关注被继承时,继承应用于整个写关注哈希,而不是单个元素。例如,在以下情况下,`j: true`不会被继承

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 1, j: true})
collection = client[:artists, write_concern: {w: 2}]
collection.write_concern.options
# => #<Mongo::WriteConcern::Acknowledged:0x47289650367880 options={:w=>2}>

尽管CRUD操作接受一个选项哈希,但它们目前不认可`:write_concern`选项

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
collection = client[:artists, write_concern: {w: :majority}]
# Still uses w: :majority
collection.insert_one({name: 'SUN Project'}, write_concern: {w: 1})

解决这个问题最简单的方法是使用#with获取具有所需写关注的新集合实例

# Uses w: 1
collection.with(write_concern: {w: 1}).insert_one(name: 'SUN Project')

写关注还可以在Database#command中手动指定

client.database.command(create: 'foo-collection', writeConcern: {w: :majority})

请注意,这里的writeConcern是操作的一部分,而不是选项,其语法是MongoDB服务器认可的驼峰式,而不是Ruby驱动程序使用的下划线式。

从Mongo Ruby驱动程序版本2.18.0开始,可以支持处理以美元符号($)开头的字段和包含点(.)的字段。在驱动程序版本2.17.0及之前,任何尝试处理点或美元字段的行为都会引发一个IllegalKey错误。有关如何处理此类字段的信息,请参阅MongoDB文档中的带点(.)和美元符号($)的字段名称

由于BSON规范已弃用BSON符号类型,当单独使用时,bson gem会将Ruby符号序列化为BSON字符串。然而,为了与旧数据集保持向后兼容,Ruby驱动程序覆盖了此行为,将Ruby符号序列化为BSON符号。这是为了能够指定包含BSON符号字段文档的查询。尽管如此,不应将具有符号类型字段的新的文档存储在数据库中;相反,应使用字符串字段。

要覆盖默认行为并配置驱动程序以将符号值编码为字符串,请将以下代码片段包含到您的项目中

class Symbol
def bson_type
BSON::String::BSON_TYPE
end
end

返回

数据处理