For each database, addition, deletion, modification, and query are essential. First, we will introduce add, that is, insert.
To compare the four operations, insert is the simplest in MongoDB. The insret command is used to insert data in MongoDB. Before using this command, we will first introduce operations such as creating databases and viewing collections.
Create a database
Use the use database name in MongoDB to create a new database, but remember that after using this command, MongoDB will not create a database immediately, the database can be viewed only after data is inserted into it. Let's look at the following example:
> Show dbslocal0.078125gb> Use newswitched to DB new> dbnew> show dbslocal0.078125gb>
AboveCodeWe use the shwo DBS command, which is used to view the current database. We can see that although we switched the database to new, we still cannot view the database using show DBS. We continue with the aboveProgramContinue writing:
> DB. c1.insert ({name: "xiangyue"})> show dbslocal0.078125gbnew0.203125gb>
At this time, we can see the new database. For the set, when there is no data, it cannot be seen. The view command of the set is:
Show tablesshow collectios
Insert data
Two Insert methods are provided in MongoDB: insert and save.
We can see that both inser and save can be inserted successfully, and the _ ID key is automatically added to the inserted document. This can be understood as the primary key of the document, it is automatically generated by MongoDB.
The difference between SAVE and insert is that if the _ ID of the inserted data is the same, save will update this document, and insert will report an error.
In this example, we insert a document with _ ID 3. When we insert the same document with insert, an error is returned. However, we succeeded in using save. We checked the document and MongoDB updated it for us. The find method used here is to view all the documents in the Set, which will be detailed later.