Basic usage of mongodb

Time:2020-8-14

Basic usage of mongodb

The main details are in http://www.runoob.com/mongodb…

This note is the most basic use of notes

My mongodb is in/usr/local/Cellar/mongodb/4.0.4_1/bin/Inside, CD into this

It must be first./mongodAnd then use it again./mongoStart Mongo at the terminal

  • If you want to turn off mongod, you can press Q to leave, or you cantopView the relevant processes, and thenkill pid

Basic understanding of mongodb

SQL terms / concepts Mongodb terms / concepts Explanation / explanation
database database database
table collection Database tables / collections
row document Data record line / document
column field Data fields / fields
index index Indexes
table joins Table connection, not supported by mongodb
primary key primary key Primary key, mongodb will automatically_ The ID field is set to the primary key

Through the example in the figure below, we can also understand some concepts in Mongo more intuitively

Basic usage of mongodb

database

A mongodb can have multiple databases

> db
text
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

useuse dbnameTo use the specified database

The database name should be all lowercase

file

A document is a set of key value pairs (bson). Mongodb documents do not need to set the same fields, and the same fields do not need the same data type, which is very different from the relational database, which is also a very prominent feature of mongodb.

RDBMS MongoDB
database database
form aggregate
That’s ok file
column field
Table Union embed document
Primary key Primary key (mongodb provides that the key is_ id )

The collection is the document group of mongodb, and the key value pairs are stored in the collection

Mongodb create database

>use tablename
  • If the database exists, it will be transferred to the current database. If not, a new database will be created automatically
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
The above three databases are provided by the system
  • You will find that the newly created database is not in it. If you want to insert data, it will be displayed in it
> db.text.insert ({"name": "treasure", "age": "18", "sex": "female"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
text    0.000GB

be careful: In mongodb, a collection can only be created after the content is inserted. That is to say, after the collection (data table) is created, another document (record) must be inserted to create the collection.

Deleting databases and collections

Delete database

1. Switch to DB: > use dbname
2.db.dropDatabase()

Delete collection

The basic grammar is as follows:

db.collection.drop()

Actual operation:

1.>use dbname
2.>show tables
after this there will show tablenames(collectionname)
3.>db.tablename.drop()

Create collection

Used in mongodbcreateCollection()Method to create a collection.

Grammar format:

db.createCollection(name, options)

Parameter Description:

  • Name: the name of the collection to be created
  • Options: optional parameter that specifies options about memory size and index

Options can be the following parameters:

field type describe
capped Boolean (optional) if true, creates a pinned collection. A fixed collection is a collection with a fixed size. When it reaches the maximum value, it will automatically cover the earliest document.When the value is true, the size parameter must be specified.
autoIndexId Boolean (optional) if true, the_ The ID field creates the index. The default is false.
size numerical value (optional) specifies a maximum value in bytes for the fixed collection.This field also needs to be specified if capped is true.
max numerical value (optional) specifies the maximum number of documents in the fixed collection.

When inserting a document, mongodb first checks the size field of the fixed set, and then the max field.

Create a fixed collection mycol, the space size of the whole collection is 6142800 KB, and the maximum number of documents is 10000.

> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 
   6142800, max : 10000 } )
{ "ok" : 1 }
>

In mongodb, you don’t need to create collections. Mongodb automatically creates collections when you insert some documents.

> db.mycol2 . insert ({"name": "rookie tutorial"})
> show collections
mycol2
...

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)

example

> use test
switched to db test
> db.col.insert ({Title: 'tutorial',})
WriteResult({ "nInserted" : 1 })
> db.col.insert ({Title: 'tutorial', desc: 'mongodb is a NoSQL', by: 'Sanjin'})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_ ID ": objectid (" 5c385b537337b5560d874451 ")," title ": tutorial"}
{ "_ ID ": objectid (" 5c385b7d7337b5560d874452 ")," title ":" tutorial "," desc ":" mongodb is a NoSQL "," by ":" Sanjin "}

It can be seen from the above content that there can be multiple collections in a document. The contents in the collection can be different. The collection can be the integration of any content, for example:

Document = ({Title: 'mongodb tutorial', 
Description: 'mongodb is a NoSQL database',
By: 'rookie tutorial',
url: 'http://www.runoob.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
});
In direct insertion, you can also:
> db.col.insert(document)
WriteResult({ "nInserted" : 1 })

After version 3.2, the following syntax can be used to insert documents:

  • db.collection.insertOne (): inserts a piece of document data into the specified collection
  • db.collection.insertMany (): insert multiple document data into the specified collection. The parameters in this parameter can put multiple sets into a list for inserting multiple document data

Mongodb updates documents to update documents in the collection

Update() method

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

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

Query: the query condition of update, similar to where in SQL update query.
Update: the object of update and some updated operators (such as $, $Inc...) can also be understood as the
Upsert: optional. This parameter means whether to insert objnew if there is no update record. True is insert. The default value is false and no insert is required.
Multi: optional. Mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found will be updated.
Writeconcern: optional, the level of exception thrown.
db.col.update ({'title':'mongodb tutorial '}, {$set: {' title ':'mongodb'}})

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

> db.col.update ({'title':'mongodb tutorial '}, {$set: {' title ':'mongodb'}}{ multi:true }

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

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

Recommended Today

Less cycle

In this section, we will learn the loop in less. Loops should be very common in programming languages. There are loops in general programming languages, such as in JavaScriptforCirculationwhileHowever, there are no such two kinds of syntax in less, but they are used to realize the loop through its own call. The use of recycling […]