本文介绍 MongoDB 中插入文档操作,详细内容参考 Insert Documents
insertOne()
db.collection.insertOne(),往集合中插入一个文档,成功之后会返回之前插入文档的 _id 字段。用法:
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
示例1:
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
示例2,设置超时时间:
db.products.insertOne(
{ "item": "envelopes", "qty": 100, type: "Self-Sealing" },
{ writeConcern: { w : "majority", wtimeout : 100 } }
);
insertMany()
db.collection.insertMany(),往集合插入多个文档,此方法需要传入一个文档数组。
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
示例1:
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" } }
])
insert()
db.collection.insert(),通过此方法往集合中插入一个或多个文档。
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
save()
db.collection.save():根据传入的参数,更新已存在的文档或插入新文档。MongoDB不建议使用 db.collection.save() ,推荐使用 db.collection.insertOne() 或 db.collection.replaceOne() 。
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
决定 save() 是插入还是更新操作,取决于 _id 参数,如果能根据 _id 找到一个已经存在的文档,那么就更新。如果没有传入 _id 参数或者找不到存在的文档,那么就插入一个新文档。
示例1:
db.products.save( { _id: 100, item: "water", qty: 30 } )
示例2:
db.products.save(
{ item: "envelopes", qty : 100, type: "Clasp" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)
其他插入文档方法
- db.collection.bulkWrite():批量写入操作
- 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.