1 MongoDB insert

插入单个文档
db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )
如果没有指定_id,mongodb会自动添加_id字段,值为:ObjectId("618101574df71602257491fa")
 
插入多个文档
基本和插入单个文档类似,传入为数组。
db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ])
 
注意:
1.在mongodb中,合集会在插入文档时自动创建,也可以提前创建。
2.在mongodb中,每一个文档必须有一个名为_id的主键,如果插入时忽略了,mongodb的驱动会自动为其加上ObjectId("xxxx")作为_id的值,这也适用于通过upsert: true更新操作插入的文档。
3.MongoDB中的所有写操作在单个文档级别上都是原子的。有关MongoDB和原子性的更多信息,请参阅原子性和事务
4.对于写入安全,您可以指定MongoDB以进行写入操作所请求的确认级别。有关详细信息,请参阅写安全
 
 
MongoDB提供了以下方法来将文档插入集合:
Inserts a single document into a collection.
db.collection.insertMany() inserts multiple documents into a collection.
db.collection.insert() inserts a single document or multiple documents into a collection.
 
用于插入的其他方法
以下方法还可以向集合中添加新文档
 
 
 

posted @ 2021-11-03 20:57  aoeiuv  阅读(75)  评论(0编辑  收藏  举报