目录
insert插入文档
本文讲述MongoDB的insert操作,通过mongoShell演示。
提示: 若当前集合不存在,则insert操作自动创建。
插入单文档
db.collection.insertOne()
方法向集合中插入单个文档。
下面的例子演示了向inventory集合中插入一个新文档。若未给文档指定_id字段,MongoDB自动为新文档添加ObjectId类型的_id字段。
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
insertOne()执行返回文档_id:
{
"acknowledged" : true,
"insertedId" : ObjectId("5b529f7371fd3aefbaa94716")
}
查询刚刚插入的文档:
db.inventory.find( { item: "canvas" } )
返回结果:
{
"_id" : ObjectId("5b529f7371fd3aefbaa94716"),
"item" : "canvas",
"qty" : 100.0,
"tags" : [
"cotton"
],
"size" : {
"h" : 28.0,
"w" : 35.5,
"uom" : "cm"
}
}
插入多文档
db.collection.insertMany()
方法可通过传入文档数组的方式向集合插入多个文档。
下面向inventory集合中插入三个文档,若未给文档指定_id字段,MongoDB自动为新文档添加ObjectId类型的_id字段。
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("5b52a22b71fd3aefbaa94717"),
ObjectId("5b52a22b71fd3aefbaa94718"),
ObjectId("5b52a22b71fd3aefbaa94719")
]
}
可通过find()方法查看全部集合文档或指定过滤器或条件查询:
db.inventory.find( {} )
插入行为
集合创建
若当前集合不存在,则insert操作自动创建。
_id字段
在MongoDB中,任何文档都需要有_id字段,且作为主键。若未给文档指定_id字段,MongoDB自动为新文档添加ObjectId类型的_id字段。
这同样适用于通过upsert插入的文档;
原子性
所有基于单文档的写操作都是原子的。see Atomicity and Transactions
写操作应答
With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.
插入方法
MongoDB提供以下插入文档的方法:
db.collection.insertOne() |
Inserts a single document into a collection. |
db.collection.insertMany() |
db.collection.insertMany() inserts multiple documents into a collection. |
db.collection.insert() |
db.collection.insert() inserts a single document or multiple documents into a collection. |
其他可插入文档的方法:
db.collection.update()
when used with theupsert: true
option.db.collection.updateOne()
when used with theupsert: true
option.db.collection.updateMany()
when used with theupsert: true
option.db.collection.findAndModify()
when used with theupsert: true
option.db.collection.findOneAndUpdate()
when used with theupsert: true
option.db.collection.findOneAndReplace()
when used with theupsert: true
option.db.collection.save()
.db.collection.bulkWrite()
.