MongoDB database -- data addition and deletion

Posted by jpadie on Wed, 12 Jan 2022 07:24:01 +0100

catalogue

1, Create database

1. Grammar

2. Instance

2, Delete database

1. Grammar

2. Instance

3. Delete collection

3, Insert document

1. Insert document

2. Instance

4, Delete document

1. Grammar

2. Instance

5, Update document

1. updata() method

2. Instance

3. save() method

4. Instance

5. More examples

6. Supplementary operators:

1, Create database

1. Grammar

Create database syntax format:

         use DATABASE_NAME

If the database does not exist, create it, otherwise switch to the database

2. Instance

Create database mongo

> use mongo  
switched to db mongo  
> db 
mongo 
>   

To view all databases, use the: show dbs command:

> show dbs  
local  0.078GB  
test   0.078GB  
>  

You can see that the database mongo we just created is not in the database list. To display it, we need to insert some data into the mongo database.

> db.mongo.insert({"name":"mongodb Study notes"})
WriteResult({ "nInserted" : 1 })  
> show dbs  
local   0.078GB  
mongo  0.078GB 
test    0.078GB  

The default database in MongoDB is test. If you do not create a new database, the collection will be stored in the test database

2, Delete database

1. Grammar

Syntax for deleting a database:

        db.dropDatabase()

Delete the current database. The default is test. You can use the db command to view the current database name

2. Instance

Delete the mongo I created. First, let's view all databases:

> show dbs  
local   0.078GB  
mongo   0.078GB  
test    0.078GB

Then switch to the mongo database

> use runoob  switched to db mongo  >

Execute the delete command:

> db.dropDatabase()  { "dropped" : "runoob", "ok" : 1 }
> show dbs  
local  0.078GB  
test   0.078GB  
> 
You can see that the deletion was successful

3. Delete collection

The syntax format of collection deletion is as follows:

        db.collection.drop()

3, Insert document

The data structure of the document is basically the same as that of JSON.

All data stored in the collection is in BSON format.

BSON is a binary storage format of json, which is called Binary JSON for short

1. Insert document

MongoDB uses the insert() or save() method to insert documents into the collection. The syntax is as follows:

        db.COLLECTION_NAME.insert(document)

2. Instance

Insert document:

>db.col.insert({title:'MongoDB Study notes',
                description:'MongoDB It's a Nosql database',
                by:'CSDN Professional development community',
                url:'www.csdn.net',
                tags: ['mongodb', 'database', 'NoSQL'],
            	likes: 100 
}) 

col is the name of our collection. We created it in the previous chapter. If the collection is not in the database, MongoDB will automatically create the collection and insert the document.

To insert a document, you can also use dB Col.save (document) command. If not specified_ The id field save() method is similar to the insert() method. If specified_ id field, the is updated_ id data.

4, Delete document

The MongoDB remove() function is used to remove data from the collection.

MongoDB data update can use the update() function. It is a good habit to execute the find() command before executing the remove() function to determine whether the execution conditions are correct.

1. Grammar

Basic syntax format of remove() method:

db.collection.remove( 
	<query>,     
	<justOne> 
)  

If your MongoDB is later than version 2.6, the syntax format is:

db.collection.remove(     
	<query>,     
	{       
		justOne: <boolean>,
		writeConcern: <document> 
	} 
)

Parameter Description:

  • query: (optional) the condition of the deleted document.
  • justOne: (optional) if set to true or 1, only one document will be deleted.
  • writeConcern: (optional) the level at which the exception was thrown.

2. Instance

We perform two insert operations:

>db.col.insert({title:'MongoDB Study notes',
                description:'MongoDB It's a Nosql database',
                by:'CSDN Professional development community',
                url:'www.csdn.net',
                tags: ['mongodb', 'database', 'NoSQL'],
            	likes: 100 
}) 

Use the find() function to query data:

> db.col.find()  
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB Study notes", "description" : 
"MongoDB It's a Nosql database", "by" : "CSDN Professional development community", "url" : "www.csdn.net", "tags" : [ 
"mongodb", "database", "NoSQL" ], "likes" : 100 }  
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB Study notes", "description" : 
"MongoDB It's a Nosql database", "by" : "CSDN Professional development community", "url" : "www.csdn.net", "tags" : [ 
"mongodb", "database", "NoSQL" ], "likes" : 100 } 

Next, we remove the document with the title 'MongoDB learning notes':

>db.col.remove({'title':'MongoDB Study notes'})  WriteResult({ "nRemoved" : 2 }) # Two pieces of data were deleted  
>db.col.find()  ......                                        # no data  

If you only want to delete the first found record, you can set justOne to 1, as shown below:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

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

>db.col.remove({})  
>db.col.find()  
>

5, Update document

1. updata() method

The update() method is used to update existing documents. The syntax format is as follows:

db.collection.updata(
        <query>,
        <updata>,
        {
                upsert:<boolean>,
                multi:<boolean>,
                writeConcern:<document>
        }
)

Parameter Description:

  • Query: query criteria of update, similar to the query criteria after where in sql update query.
  • Update: update object and some Update Operators (such as $, $inc...) And so on, which can also be understood as the data after the set in the sql update query
  • upsert: optional. This parameter means whether to insert objnew if there is no update record. True means insert. The default is false and not insert.
  • multi: optional. mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found by conditions will be updated.
  • writeConcern: optional, the level of exception thrown.

2. Instance

We use the updata() method to update the title in the collection col:

>db.col.update({'title':'MongoDB Study notes'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   # Output information 

> db.col.find().pretty()  
{         
	"_id" : ObjectId("56064f89ade2f21f36b03136"),  
	"title" : "MongoDB",   
	"description" : "MongoDB It's a Nosql database",  
	"by" : "CSDN Professional development community",      
	"url" : "www.csdn.net", 
	"tags" : [   
		"mongodb",   
		"database",   
		"NoSQL"      
	],      
	"likes" : 100  
}  

The above statement will only modify the first found document. If you want to modify multiple identical documents, you need to set the multi parameter to true.

>db.col.update({'title':'MongoDB Study notes'},{$set:{'title':'MongoDB'}},{multi:true})

3. save() method

The save() method replaces the existing document with the incoming document. The syntax format is as follows:

db.collection.save(
        <document>,
        {
                writeConcern:<document>
        }
)

Parameter Description:

  • Document: document data.
  • writeConcern: optional, the level of exception thrown

4. Instance

In the following example, we replaced_ Document data with id asdfghjkl1234567890 +

>db.col.save({  	
	"_id" : ObjectId("Asdfghjkl234567890"),   
	"title" : "MongoDB",  
	"description" : "MongoDB It's a Nosql database",    
	"tags" : [           
		"mongodb",       
		"NoSQL"    
	],    
	"likes" : 110
	}
)

Use the find() command to view:

>db.col.find().pretty()
{  	
	"_id" : ObjectId("Asdfghjkl234567890"),   
	"title" : "MongoDB",  
	"description" : "MongoDB It's a Nosql database",    
	"tags" : [           
		"mongodb",       
		"NoSQL"    
	],    
	"likes" : 110
}

5. More examples

Update only the first record:

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

Update all:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

Add only the first:

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

Add all:

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

Update all:

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 );

6. Supplementary operators:

  • (>) greater than - $gt
  • (<) less than - $lt
  • (> =) greater than or equal to - $gte
  • (< =) less than or equal to - $lte

Topics: Database