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. 使用git下载编译erlang

    git clone https://github.com/erlang/otp cd otp git tag git checkout -b OTP- OTP- ./otp_build all exp ...

  2. 复利计算1.0,2.0,3.0(java)

    程序源代码: import java.util.Scanner; public class ch { public static void main(String[] args) { Scanner ...

  3. 第五周PSP &进度条

    团队项目PSP 一:表格     C类型 C内容 S开始时间 E结束时间 I时间间隔 T净时间(mins) 预计花费时间(mins) 讨论 讨论用户界面 9:27 10:42 18 57 60 分析与 ...

  4. 【剑指offer】Java实现(持续更新中)

    面试题3 二维数组中的查找 Leetcode--74 Search a 2D Matrix /*Java Write an efficient algorithm that searches for ...

  5. PAT 甲级 1077 Kuchiguse

    https://pintia.cn/problem-sets/994805342720868352/problems/994805390896644096 The Japanese language ...

  6. spring mvc $.ajax没有指定contentType ,导致后台无法接收到数据

    var formData = JSON.stringify(this.rows); //将表单中的数据转为字符串 $.ajax({ type: "post", url: 'http ...

  7. java 基础 --Collection(Map)

    Map是不是集合?哈哈哈 java编程思想>的第11章,第216页,正数第13行,中原文:“……其中基本的类型是LIst.Set.Queue和Map.这些对象类型也称为集合类,但由于Java类库 ...

  8. 使用Dede破解Delphi软件实战

    昨日练习了一把如何破解Delphi软件.下面和大家分享一下破解的过程,对初学者,希望有授之以渔的作用. 首先分析我们的目标软件,不要问我破解的是什么软件.保护知识产权,要从娃娃抓取. 目标软件是一个销 ...

  9. day 05 万恶之源-基本数据类型(dict)

    05. 万恶之源-基本数据类型(dict)本节主要内容:1. 字典的简单介绍2. 字典增删改查和其他操作3. 字典的嵌套⼀一. 字典的简单介绍字典(dict)是python中唯⼀一的⼀一个映射类型.他 ...

  10. 题解 P1469 【找筷子】

    这题真是水 咳咳.. 基本思路:桶排 但是可以剪枝. 剪枝方法: 好几种,可以用set(集合),可以用stack(栈), 也可以像我一样的蒟蒻最大最小值...... 但是作者的毒瘤数据应该不会放过我们 ...