[Mr. Zhao Qiang] mongodb insert document

Time:2021-10-17

Mongodb is the representative of non relational database NoSQL. As a distributed storage database, the operation of documents is the top priority of mongodb. In this article, we will focus on how to insert documents in mongodb.

Mongodb provides us with three ways to insert documents:

  • DB. Collection. Insertone(): inserts a specified document
  • DB. Collection. Insertmany(): insert multiple specified documents
  • DB. Collection. Insert(): inserts one or more specified documents

A new document can be inserted into a collection using the insert statement. If the collection does not already exist, the insert statement will automatically create the collection.

1、 DB. Collection. Insertone(): inserts a specified document

db.collection.insertOne(
   ,
   {
      writeConcern: 
   }
)

Example:Insert a piece of student data:

2、 DB. Collection. Insertmany(): insert multiple specified documents

db.collection.insertMany(
   [  , , ... ],
   {
      writeConcern: ,
      ordered: 
   }
)

The above method mainly has three parameters:

  • Document – this parameter refers to the data of one or more documents to be inserted. If it is a document, this parameter is a JSON data. If it is multiple documents, this parameter is an array composed of multiple JSON data.
  • Writeconcern – optional parameter. This parameter refers to the write concern of the insertion operation. Its value is a document, represented as JSON data. You can refer to the previous explanation.
  • Ordered – new parameters after version 2.6, optional. If the value is true, the documents in the array will be inserted orderly. If a document has an error, mongodb will return without processing the remaining documents in the array. If false, unordered insertion is performed. If the error occurs in a document, the remaining documents in the array continue to be processed. The default is true.

Example:

3、 DB. Collection. Insert(): inserts one or more specified documents, that is, the unification of insertone and insertmany

The syntax format is as follows:

db.collection.insert(
   ,
   {
     writeConcern: ,
     ordered: 
   }
)

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]