MongoDB provides the following methods for inserting documents into a collection:

This page provides examples of insert operations in the mongo shell.

Insert Behavior

Collection Creation

If the collection does not currently exist, insert operations will create the collection.

_id Field

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

This also applies to documents inserted through update operations with upsert: true.

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions

db.collection.insertOne()

New in version 3.2.

db.collection.insertOne() inserts a single document into a collection.

The following example inserts a new document into the users collection. The new document has three fields nameage, and status. Since the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document. See Insert Behavior.

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

insertOne() will return a document providing the inserted document’s _id field. See the reference for an example.

To retrieve the document that you just inserted, query the collection:

For more information and examples, see db.collection.insertOne().

db.collection.insertMany()

New in version 3.2.

db.collection.insertMany() inserts multiple documents into a collection.

The following example inserts three new documents into the users collection. Each document has three fields nameage, and status. Since the documents do not specify an _id field, MongoDB adds the _idfield with an ObjectId value to each document. See Insert Behavior.

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

insertMany() will return a document providing each inserted document’s _id field. See the reference for an example.

To retrieve the inserted documents, query the collection:

db.users.find()

For more information and examples, see db.collection.insertMany().

db.collection.insert()

db.collection.insert() inserts a single document or multiple documents into a collection. To insert a single document, pass a document to the method; to insert multiple documents, pass an array of documents to the method.

The following example inserts a new document into the users collection. The new document has three fields nameage, and status. Since the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the document. See Insert Behavior.

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

db.collection.insert returns a WriteResult object providing status information.

For example, a successful insert returns the following WriteResult object:

WriteResult({ "nInserted" : 1 })

The nInserted field specifies the number of documents inserted. If the operation encounters an error, the WriteResult object will contain the error information.

The following example inserts multiple documents into the users collection. Since the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document. See Insert Behavior.

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

The method returns a BulkWriteResult object with the status of the operation. A successful insert of the documents returns the following BulkWriteResult object:

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

For more information and examples, see db.collection.insert().

Additional Methods

The following methods can also add new documents to a collection:

See the individual reference pages for the methods for more information and examples.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

MongoDB - MongoDB CRUD Operations, Insert Documents的更多相关文章

  1. MongoDB - MongoDB CRUD Operations, Delete Documents

    Delete Methods MongoDB provides the following methods to delete documents of a collection: Method De ...

  2. MongoDB - MongoDB CRUD Operations, Update Documents

    Update Methods MongoDB provides the following methods for updating documents in a collection: Method ...

  3. MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell

    The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...

  4. MongoDB - MongoDB CRUD Operations, Query Documents, Query for Null or Missing Fields

    Different query operators in MongoDB treat null values differently. The examples on this page use th ...

  5. MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query

    By default, queries in MongoDB return all fields in matching documents. To limit the amount of data ...

  6. MongoDB - MongoDB CRUD Operations, Query Documents

    Query Method MongoDB provides the db.collection.find() method to read documents from a collection. T ...

  7. MongoDB - MongoDB CRUD Operations

    CRUD operations create, read, update, and delete documents. Create Operations Create or insert opera ...

  8. MongoDB - MongoDB CRUD Operations, Bulk Write Operations

    Overview MongoDB provides clients the ability to perform write operations in bulk. Bulk write operat ...

  9. Mongodb系列- CRUD操作介绍

    ---恢复内容开始--- 一 Create 操作 在MongoDB中,插入操作的目标是一个集合. MongoDB中的所有写入操作在单个文档的层次上都是原子的. For examples, see In ...

随机推荐

  1. a5

    今日内容: 今天主要还是素材的查找,图标的制作以及调整. 明日计划: 主要还是完成图标,尽可能的美化 困难: 一个是直男式的审美吧,另一个是PS的技术还不够深

  2. c语言的知识与能力自评

    知识与能力 C语言最早是由美国Bell实验室设计的,主要用作UNIX系统的工作语言,后来发展成为一种通用语言.C与UNIX有密切的关系,C最早是在PDP机器上用UNIX操作系统上开发的,后来又用C语言 ...

  3. 重写JdbcRDD支持Sql命名参数和分区

    Spark提供的JdbcRDD很不好用,没法指定命名参数,而且必须要提供两个Long类型的参数表示分区的范围,如果数据表没有long类型的字段或者不需要条件,那就不能用JdbcRDD了.这里我简单重写 ...

  4. zabbix简介

    (一)监控系统 初探 前言: 对于监控系统而言,首先必须搞清楚需要监控什么? (1)硬件设备和软件设备:服务器,路由器,交换机,I/O存储系统,操作系统,网络,各种应用程序 (2)各种指标:数据库宕机 ...

  5. python获取前几天的时间

    days的参数就是你想获取前多少天的数据,如果是昨天的话,则days=1 import datetime today=datetime.date.today() oneday=datetime.tim ...

  6. Java String简单知识点总结

    1.字符串的比较 public void run(){ //str1在池中 String str1 = new String("String"); //str2,str3 存在于堆 ...

  7. 【第一周】c++实现词频统计

    coding.net地址:https://coding.net/u/Boxer_ ssh:git@git.coding.net:Boxer_/homework.git ---------------- ...

  8. 【BioCode】读文件夹以发现缺失文件

    代码说明: 使用单个蛋白质的txt计算PSSM生成的结果为单个的PSSM文件. 但是由于一些原因(如蛋白质序列过长),会导致一些蛋白质txt文件无法计算出pssm,为了找到这些没有计算出pssm的蛋白 ...

  9. flink ha zk集群迁移实践

    flink为了保证线上作业的可用性,提供了ha机制,如果发现线上作业失败,则通过ha中存储的信息来实现作业的重新拉起. 我们在flink的线上环境使用了zk为flink的ha提供服务,但在初期,由于资 ...

  10. Java容器深入浅出之String、StringBuffer、StringBuilder

    对字符串的花式处理一直是现代应用系统的主要操作之一,也是对Java基础知识考察的重要方面.事实上,Java字符串类的底层是通过数组来实现的.具体来说,String类是固定长度的数组,StringBuf ...