翻译或纠错本页面

插入文档

插入方法

MongoDB提供了如下方法向集合插入 文档 documents :

本页提供了 :program:在 mongo shell中插入操作的示例.

插入操作的行为表现

创建集合

插入的时候如果集合不存在,那么插入操作会创建集合。

_id 字段

在MongoDB中,存储于集合中的每一个文档都需要一个唯一的 _id 字段作为 primary_key。如果一个插入文档操作遗漏了``_id`` 字段,MongoDB驱动会自动为``_id``字段生成一个 ObjectId

这种情况同样适用于通过带有参数 upsert: true 的update操作来插入文档的情况。

原子性

MongoDB中所有的写操作在单一文档层级上是原子的.更多关于MongoDB和原子性的信息,请参见 原子性和事务处理.

db.collection.insertOne()

3.2 新版功能.

db.collection.insertOne() 向集合插入 单个 文档 document .

如下的示例向 users 集合插入了一个新的文档。新的文档有三个字段 name,``age``,和 status。 由于该文档未指定 _id 字段,MongoDB 向该新文档添加了值为 ObjectId_id 字段。参见 插入操作的行为表现.

db.users.insertOne(
   {
      name: "sue",
      age: 19,
      status: "P"
   }
)

You can run this method in the web shell below:

insertOne() 返回一个结果文档,该结果文档中列举了插入文档的``_id`` 字段值。 具体例子请参考::ref:<insertOne-examples>。

为了验证插入了文档,通过指定 _id 字段上的查询过滤条件 query the collection:

db.users.find( { "name": "sue" } )

更多信息和例子请参考: db.collection.insertOne()

db.collection.insertMany()

3.2 新版功能.

db.collection.insertMany() 向集合插入 多个 文档

如下的示例向 users 集合插入了三个新的文档。每个文档有三个字段 name,``age``和 status。由于这些文档未指定 _id 字段,MongoDB 向每个新文档添加了值为 ObjectId_id 字段。 具体参见 插入操作的行为表现.

db.users.insertMany(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)

You can run this method in the web shell below:

insertMany() 将返回一个结果文档,文档中包含了每一个插入文档的``_id``字段。 具体例子请参考 <insertMany-examples>

验证插入的文档,可以参考 查询集合:

db.users.find()

更多详情和例子请参考: db.collection.insertMany()

db.collection.insert()

db.collection.insert() 向集合插入一个或多个文档.要想插入一个文档,传递一个文档给该方法;要想插入多个文档,传递文档数组给该方法.

如下的示例向 users 集合插入了一个新的文档.新的文档有三个字段 name,``age``,和 status.由于该文档未指定 _id 字段,MongoDB 向该文档添加了值为 ObjectId_id 字段.参见 插入操作的行为表现.

db.users.insert(
   {
      name: "sue",
      age: 19,
      status: "P"
   }
)

You can run this method in the web shell below:

db.collection.insert() 返回一个包含状态信息的 WriteResult 对象。

该操作返回了含有操作状态的 WriteResult 对象.插入文档成功返回如下 WriteResult 对象:

WriteResult({ "nInserted" : 1 })

nInserted 字段指明了插入文档的总数.如果该操作遇到了错误, WriteResult 对象将包含该错误信息.

如下的示例向 users 集合插入了多个文档.由于这些文档未指定 _id 字段,MongoDB 向每个新文档添加了值为 ObjectId_id 字段.参见 插入操作的行为表现.

db.users.insert(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)

该方法返回了包含操作状态的 BulkWriteResult 对象.成功插入文档返回如下 BulkWriteResult 对象:

BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

更多详情和例子请参考: db.collection.insert()

其他方法

以下方法也可以向集合中添加新文档:

更多信息和例子请参见该方法的参考页。

写确认

在安全写情况下,你可以指定MongoDB写操作要求的确认级别,详细请参考 Write Concern