如果集合当前不存在,则插入操作将创建集合。
文章目录
插入单个文档
> db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8f5d9ae161d7c69f0cb263")
}
insertone()返回一个包含新插入文档的id字段值的文档。有关返回文档的示例,请参见db.collection.insertone() reference.。
要检索刚插入的文档,请查询集合:
> db.inventory.find( { item: "canvas" } )
{ "_id" : ObjectId("5c8f5d9ae161d7c69f0cb263"), "item" : "canvas", "qty" : 100, "tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }
插入多个文档
3.2版本新增功能
> 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" } }
])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5c8f5e8ee161d7c69f0cb264"),
ObjectId("5c8f5e8ee161d7c69f0cb265"),
ObjectId("5c8f5e8ee161d7c69f0cb266")
]
}
insertone()返回一个包含新插入文档的id字段值的文档。有关返回文档的示例,请参见 reference.
要检索刚插入的文档,请查询集合:
> db.inventory.find( {} )
mongoDB是怎样插入文档的
-
创建集合
如果集合当前不存在,就创建集合。 -
_id 字段
在MongoDB中,存储在集合中的每个文档都需要一个唯一的ID字段作为主键。如果插入的文档省略了_id字段,MongoDB驱动程序会自动为_id字段生成一个objectid。 -
原子性
MongoDB中的所有写操作都是单文档级别的原子操作 -
写确认
您可以指定MongoDB为写操作请求的确认级别。有关详细信息,请参阅写关注。
插入方法
方法 | 描述 |
---|---|
db.collection.insertOne() | 插入单个文档到集合 |
db.collection.insertMany() | 插入多个文档到集合 |
db.collection.insert() | 插入单/多个文档到集合 |
以下方法还可以将新文档添加到集合中
- db.collection.update() when used with the upsert: true option.
- db.collection.updateOne() when used with the upsert: true option.
- db.collection.updateMany() when used with the upsert: true option.
- db.collection.findAndModify() when used with the upsert: true option.
- db.collection.findOneAndUpdate() when used with the upsert: true option.
- db.collection.findOneAndReplace() when used with the upsert: true option.
- db.collection.save().
- db.collection.bulkWrite().
原文:https://docs.mongodb.com/manual/tutorial/insert-documents/#write-op-insert-behavior
https://docs.mongodb.com/manual/reference/insert-methods/