MongoDB:插入文档

本文介绍了MongoDB插入文档的相关知识。若集合不存在,插入操作会创建集合。插入单个文档用db.collection.insertOne(),插入多个文档用db.collection.insertMany()。还说明了MongoDB插入文档时的_id字段、原子性、写确认等内容,以及其他可添加新文档的方法。

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

如果集合当前不存在,则插入操作将创建集合。

插入单个文档

> 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/reference/insert-methods/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值