本文介绍了嵌入式文档上findAndModify的原子性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mongodb手册上,有一个示例用于单个文档的原子操作.

On mongodb manual there is an example for atomic operations on a single document.

book = {
          _id: 123456789,
          title: "MongoDB: The Definitive Guide",
          available: 3,
          checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
        }

手册指出以下操作是原子的:

The manual states that the below operation is atomic:

db.books.findAndModify ( {
   query: {
            _id: 123456789,

            available: { $gt: 0 }
          },
   update: {
             $inc: { available: -1 },
             $push: { checkout: { by: "abc", date: new Date() } }
           }
} )

我的问题是,如果可用字段是嵌入式文档,将会发生什么.如下:

My question is what would happen if available field was an embedded document. Such as below:

book = {
          _id: 123456789,
          title: "MongoDB: The Definitive Guide",
          available: [ { value: 3, valueFloat: 3.00 ] },
          checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
        }

我仍然可以自动执行此操作吗?如果可以,怎么办?

Could I still do this operation atomically? If so, how?

推荐答案

由于子文档基本上只是主文档中的字段,因此对其的任何更新也是原子的.

Since subdocuments are basically just fields within the main document any updates to them are also atomic.

MongoDB每个文档都有事务,该事务适用于整个文档,包括其子文档.

MongoDB has transactions per document and that applies to the entire document, including its subdocuments.

应注意,不仅findAndModify是原子的.单个文档上的任何操作,无论是update()还是remove()都是原子操作.

It should be noted that not just findAndModify is atomic. Any operation on a single document, whether it be update() or remove() is atomic.

这篇关于嵌入式文档上findAndModify的原子性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 07:05