MongoDB Write Operations

##Insert

  • db.collection.insertOne()
  • db.collection.insertMany()
  • db.collection.insert()

如果没有 _id字段,mongo会自动加一个


##Update

The updateOne(), updateMany(), and replaceOne() operations accept the upsert parameter. When upsert : true, if no document in the collection matches the filter, a new document is created based on the information passed to the operation.

  • db.collection.updateOne()
  • db.collection.updateMany()
  • db.collection.replaceOne()
  • db.collection.update()

db.collection.update() method can accept query criteria to determine which documents to update as well as an options document that affects its behavior, such as the multi option to update multiple documents.

  • The $set operator replaces the value of a field with the specified value.
  • $unset replaces the matching element with null
  • The $rename operator updates the name of a field

##Delete

  • db.collection.deleteOne()
  • db.collection.deleteMany()
  • db.collection.remove()

—Bulk Write—

  • db.collection.bulkWrite()

写操作对于每个document都是原子操作,bulk里操作单个document的也是原子
当一个操作要改变多个document的时候,每个document的变化是原子的,但整个批量操作不是原子的。这时候需要
isolated

db.foo.update(
{ status : "A" , $isolated : 1 },
{ $inc : { count : 1 } },
{ multi: true }
)


当你要把不同的多个操作 变成一个原子操作,你需要Transaction

https://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/


##Concurrency Control

需要有唯一的字段,让mongo知道重复了


##Performance

https://docs.mongodb.org/manual/core/write-performance/