MongoDB(2) Addendum, Delete and Modify - The Operation We Are Familiar with

Keywords: Database MongoDB shell SQL

This article describes how to start MongoDB and connect with a shell. Here are some of the operations we are familiar with in mysql
1. Create a database

MongoDB The grammatical format for creating the database is as follows:

```
use DATABASE_NAME
```

//If the database does not exist, create the database, otherwise switch to the specified database.
//Demonstration

```shell
> use zxmantou
switched to db zxmantou
> db
zxmantou
>
```
//So our current db is zxmantou. Use the ** show dbs ** command to view the database list

```shell
> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB
```
//It was found that the new database was not in it. To display it, we need to insert some data into the zxmantou database.

```shell
> db.user.insert({name:"zxmantou"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin     0.000GB
local     0.000GB
test      0.000GB
zxmantou  0.000GB
>
```
  1. Delete the database

    Delete the current database by default to test. In the following example, we will delete our new zxmantou library:

    > show dbs
    admin     0.000GB
    local     0.000GB
    test      0.000GB
    zxmantou  0.000GB
    > db
    zxmantou
    > db.dropDatabase()
    { "dropped" : "zxmantou", "ok" : 1 }
    > show dbs
    admin  0.000GB
    local  0.000GB
    test   0.000GB
  2. Delete collections (delete data tables)
    The set deletion grammar format is as follows:

    db.COLLECTION_NAME.drop()

    Example:

    > use zxmantou
    switched to db zxmantou
    > show tables
    user
    > db.user.drop()
    true
    > show tables
    >
  3. Insert Documents (New Records)
    MongoDB uses insert() or save() methods to insert documents into collections with the following syntax:

    db.COLLECTION_NAME.insert(document)

    Example:

    > use zxmantou
    switched to db zxmantou
    > db.user.insert({
    ... name:"zxmantou",
    ... age:"27",
    ... gender: "male",
    ... site: "www.zhangyuxiaojiao.com"
    ... })
    WriteResult({ "nInserted" : 1 })
    > db.user.find()
    { "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"), "name" : "zxmantou", "age" : "27", "gender" : "male", "site" : "www.zhan
    gyuxiaojiao.com" }
    >

    In the above example, user is our collection name (data table name), and if the collection is not in the database, MongoDB automatically creates the collection and inserts the document (one row record).

  4. Update Documents (Update Records)
    MongoDB uses update() and save() methods to update documents in a collection. Next, let's look at the application of the two functions and their differences in detail.

    5.1 Update() method:
    The update() method is used to update existing documents. The grammatical format is as follows:

    ```
    db.COLLECTION_NAME.update(
       <query>,
       <update>,
       {
         upsert: <boolean>,
         multi: <boolean>,
         writeConcern: <document>
       }
    )
    ```
    
        Description of parameters:
      Query: The query condition of update is similar to that of where in sql update query.
      Update: The object of update and some updated operators (e.g. $, $inc...) can also be understood as following the set in the sql update query
      upsert: Optional. This parameter means whether to insert objNew if there is no update record, true is insert, false by default, and no insert.
      multi: Optionally, mongodb defaults to false, updates only the first record found, and if this parameter is true, updates all the records found on condition.
      Write Concern: Optional, throw exception level.
    

    We have just inserted a record, and now we will modify it:

    > db.user.find()
    { "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"), "name" : "zxmantou", "age" : "27", "gender" : "male", "site" : "www.zhan
    gyuxiaojiao.com" }
    > db.user.update({'name':'zxmantou'},{$set:{'age':18}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.user.find().pretty()
    {
            "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"),
            "name" : "zxmantou",
            "age" : 18,
            "gender" : "male",
            "site" : "www.zhangyuxiaojiao.com"
    }
    >

    It can be seen that the age has been younger to 18 years old.~

    5.2 save() method
    The save() method replaces an existing document by an incoming document. The grammatical format is as follows:

    db.collection.save(
           <document>,
           {
             writeConcern: <document>
           }
        )
        Description of parameters:
            document: document data.
            Write Concern: Optional, throw exception level.    
    

    Example

    In the following example, we replace the document data with _id of 58e4d75bbe3140034aeb2ba1:

    > db.user.save({
    ... "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"),
    ...     "name" : "zhangyuxiaojiao",
    ...     "gender" : "male",
    ...     "age" : "27",
    ...     "site" : "zxmantou.github.io"
    ... })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.user.find().pretty()
    {
            "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"),
            "name" : "zhangyuxiaojiao",
            "gender" : "male",
            "age" : "27",
            "site" : "zxmantou.github.io"
    }
    >
    More examples
    • Update only the first record:

      db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );
    • All updates:

      db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );
    • Add only the first item:

      db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );
    • Add all:

      db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );
    • All updates:

      db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );
    • Update only the first record:

      db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );
  5. Delete Documents (Delete Records)
    The basic grammatical format of the remove() method is as follows:

    db.collection.remove(
       <query>,
       {
         justOne: <boolean>,
         writeConcern: <document>
       }
    )
            Description of parameters:
        query: (optional) The condition for deleting a document.
        justOne: (optional) If set to true or 1, only one document is deleted.
        Write Concern: (optional) The level at which an exception is thrown.
    

    Example:

> db.user.find().pretty()
{
        "_id" : ObjectId("58e4d75bbe3140034aeb2ba1"),
        "name" : "zhangyuxiaojiao",
        "gender" : "male",
        "age" : "27",
        "site" : "zxmantou.github.io"
}
> db.user.remove({'name':'zhangyuxiaojiao'})
WriteResult({ "nRemoved" : 1 })
> db.user.find().pretty()
>

If you want to delete all data, you can use the following method (similar to the truncate command of regular SQL):

>db.col.remove({})
  1. Query Documents (Query Records)
    Previous examples have shown how to query all records by find(), and the next article will elaborate on complex query methods.

Posted by d3web on Wed, 26 Jun 2019 12:39:23 -0700