mongodb Insert 、 remove 、操作原子性(atomicity)

本文介绍了MongoDB中插入和删除文档的方法,包括db.collection.insertOne(), db.collection.insertMany(), db.collection.remove(), db.collection.deleteOne(), 和db.collection.deleteMany()等API的使用方式。同时,还探讨了原子性及$isolated操作符的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

insert methods

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

db.collection.insert()

inserts a single document or multiple documents into a collection.
To insert a single document, pass a document to the method; to insert multiple documents, pass an array of documents to the method.

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

about ordered(Defaults to true)

Optional.
If true, perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.

If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.

Delete methods

db.collection.remove()    Delete a single document or all documents that match a specified filter.
db.collection.deleteOne()   
db.collection.deleteMany()

remove()

db.users.remove( { status : "P" } )

删除集合、数据库

db.COLLECTION_NAME.drop()
db.dropDatabase()

Atomicity

In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.

$isolated

Using the $isolated operator, a write operation that affects multiple documents can prevent other processes from interleaving once the write operation modifies the first document. This ensures that no client sees the changes until the write operation completes or errors out.

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

Without the $isolated operator, the multi-update operation will allow other operations to interleave(交错) with its update of the matched documents.

转载于:https://www.cnblogs.com/jcuan/p/5698768.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值