MongoDB Learning (I) Common MongoDB Commands

Keywords: Database MongoDB SQL JSON

1. Create a database

Create grammar:

use DATABASE_NAME

If the database does not exist, create the database, otherwise switch to the specified database.
Create yyf_mongodb database, db displays the current database

> use yyf_mongodb
switched to db yyf_mongodb
> db
yyf_mongodb

If you want to view all databases, you can use the show dbs command:

> show dbs
local  0.078GB

As you can see, the database runoob we just created is not in the list of databases. To display this database, you need to insert data into it.

> db.yyf_mongodb.insert({"name":"123"})
WriteResult({ "nInserted" : 1 })
> show dbs
local        0.078GB
yyf_mongodb  0.078GB

2. Delete the database

Delete grammar:

db.dropDatabase()

Delete the created y yyf_mongodb database

#Switch to y yyf_mongodb database
> use yyf_mongodb
switched to db yyf_mongodb
#Execute Delete Command
> db.dropDatabase()
{ "dropped" : "yyf_mongodb", "ok" : 1 }

Is the database deleted successfully by the show dbs command:

> show dbs
local  0.078GB

3. Delete collections

The set deletion grammar format is as follows:

db.collection.drop()

4. Insert Documents

The data structure of the document is basically the same as that of JSON.
MongoDB uses insert() or save() methods to insert documents into collections with the following syntax:

db.COLLECTION_NAME.insert(document)

Insert a document into y yyf_mongodb:

> db.col.insert({url:"http://localhost",
    description:'127.0.0.1',
    by:'55'})
WriteResult({ "nInserted" : 1 })

The collection is called col, and if the collection is not in the database, MongoDB automatically creates the collection and inserts the document.
View collections:

> db.col.find()
{ "_id" : ObjectId("59cdf6b516664e819555461d"), "url" : "http://localhost", "description" : "127.0.0.1", "by" : "55" }

After version 3.2, the following grammars can be used to insert documents:
db.collection.insertOne(): Insert a document data into the specified collection
db.collection.insertMany(): Insert multiple document data into a specified collection

db.collection.insertMany([{"b": 3}, {'c': 4}])

5. Update Documents

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

db.collection.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: update objects and some updated operators (e.g., inc...) It 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.
Insert a document into the collection:

> db.col.insert({url:"http://localhost", description:'127.0.0.1', by:'55'})
WriteResult({ "nInserted" : 1 })

Update the document:

> db.col.update({'by':'55'},{$set:{'by':'66'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("59cdfbb616664e819555461f"), "url" : "http://localhost", "description" : "127.0.0.1", "by" : "66" }

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

>db.col.update({'by':'55'},{$set:{'by':'66'}},{multi:true})

6. Delete documents

The basic grammatical format of the remove() method is as follows:

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

If your MongoDB is after version 2.6, the grammatical format 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.

Remove document by 66

> db.col.remove({'by':'66'})
WriteResult({ "nRemoved" : 2 })
> db.col.find()
...     #No data

If you only want to delete the record found in the first entry, you can set justOne to 1, as follows:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

It is now officially recommended to use deleteOne() and deleteMany() methods.
For example, delete all documents under a collection:

db.inventory.deleteMany({})

Delete all documents whose status equals A:

db.inventory.deleteMany({ status : "A" })

Delete a document whose status equals D:

db.inventory.deleteOne( { status: "D" } )

7. Query Documents

The grammatical format of MongoDB query data is as follows:

db.collection.find(query, projection)

Query: Optional, use query operators to specify query conditions

Projection: Optional, use the projection operator to specify the returned key. When querying, all the key values in the document are returned, and only the parameter is omitted (default omitted).

If you need to read data in a readable way, you can use the pretty() method. The grammatical format is as follows:

>db.col.find().pretty()

and Conditional Query:

>db.col.find({key1:value1, key2:value2}).pretty()

or condition query:

>db.col.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Posted by itandme on Mon, 20 May 2019 11:32:52 -0700