preface

MongoDB is a semi-structured non-relational database based on distributed file storage. In mass data, it can process access operation with high performance. It stores data in BSON format (similar to JSON format but with richer types), making it easier to save and process complex data types. At the same time, in the non-relational database lineup, it has more features than other database products, and the same type of relational database, so it can be used quickly for beginners.

The installation

Environment: CentOS 7 Version: 4.2.6 Enterprise Version: NO-security (TGZ)

The installation package

Visit the official website to download the link: www.mongodb.com/download-ce…

I’m using the Enterprise version here, and the download options are shown below:

The mongodb linux-x86_64-enterprise-rhel70-4.2.6. TGZ package is obtained

Upload the downloaded package to the corresponding directory and decompress the package

> the tar - ZXVF mongo - Linux - x86_64 - enterprise - rhel70-4.2.6. TGZCopy the code

The configuration file

The current version is security free, so mongoDB configuration files need to be created manually. If you are using the install version, the configuration file will be in /etc/mongod.conf after installation.

Before creating the configuration, create the data, log, and run directories, which correspond to the data storage directory, log directory, and process ID directory respectively

> mkdir -p /var/mongodb/data
> mkdir -p /var/mongodb/log
> mkdir -p /var/mongodb/run
Copy the code

Create mongod. Conf in /var/mongodb:

# mongod.conf

# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/mongodb/log/mongo.log Log file path setting

# Where and how to store data.
storage:
  dbPath: /var/mongodb/data # Data storage path
  journal:
    enabled: true
# engine:
# wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/mongodb/run/mongod.pid  # location of pidfile  
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017 # port
  bindIp: 127.0.0.1  # listen on IP address, can access IP address, default is local


security:
  authorization: enabled
  
#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

Copy the code

Common basic properties of configuration files:

attribute instructions
systemLog#destination Log output location, file or syslog. If file is used, path must be specified
systemLog#logAppend Whether the log is appended to the existing log when the instance is started
systemLog#path Log Storage Path
storage#dbPath Data Storage Path
storage#journal#enabled Whether logs are permanent and can be used to recover data
processManagement#fork Whether to run the service in the background
processManagement#pidFilePath Pid file storage path
processManagement#timeZoneInfo Time zone path used by the database
net#port Port used by data
net#bindIp An accessible IP address that listens to client connections
security#authorization Whether to enable permission control

Service start-stop

Add the decompressed installation package bin PATH to the /etc/profile environment variable and append it to PATH

# mongoDB
PATH=$PATH:/usr/local/ software/mongo/mongo - Linux - x86_64 - enterprise - rhel70-4.2.6 / binCopy the code

Start with the /var/mongodb/mongod.conf configuration file:

> mongod -f /var/mongodb/mongodb.conf
Copy the code

If the following information is displayed, the system is successfully started

After the startup is complete, verify that it works properly

> mongo
Copy the code

If yes, the login page is displayed

Create an account and set the role to root

> use admin
> db.createUser({user:"xxxx".pwd:"xxxxxx",roles:["root"]})
Copy the code

After the account is configured, you need to verify the account permission to log in again

> mongo -u accont -p password
Copy the code

To stop the MongoDB service, switch to the admin database

> use admin
> db.shutdownServer()
Copy the code

Basic operation

Before introducing several operations, we will compare common MongoDB objects with relational databases to better understand MongoDB objects.

MongoDB Relational database
Database (Database) Database (Database)
A Collection The Table (Table).
Document The Row (line)
Field = Field The Column (Column)

The operation of the Database

The use db command is used to create and select data

Viewing all databases

> show dbs
Copy the code

Delete database, select first and then delete

> use db
> db.dropDatabase()
Copy the code

The operation of the Collection

The create collection command, and the collection is automatically created when data is inserted if it has not been created first

> db.createCollection(collectionName, [options])
Copy the code

Options is an optional parameter, which mainly refers to the data verification rule.

View all collections in the database

> show collections
Copy the code

Choice set

Db.getcollection (collectionName) or > db.collectionNameCopy the code

Delete the collection

> db.collectionName.drop()
Copy the code

insert

MongoDB insert methods include insertOne(), insertMany(), insert(), save(). Insert () includes insertOne() and insertMany().

insertOne

InsertOne () inserts a document into the database in the syntax:

db.collect.insertOne(
    <document>,
    {
        writeConcern: <document>
    }
)
Copy the code

Parameter in insertOne() :

  • The document argument is the inserted BSON data
  • WriteConcern is an optional write policy

Insert an article collection into MongoDB’s YTAO database

db.article.insertOne(
    {
        title: "Implementation of Dubbo Load Balancing",
        url: "https://ytao.top/2020/05/02/23-dubbo-loadbalance/",
        author: "ytao"})Copy the code

The database data is:

Note: If an id is not specified when inserting data, the id will be generated automatically. If the _id is specified, it must exist in the database; otherwise, an insert failure is reported.

insertMany

The insertMany() method inserts multiple documents at once, with the syntax:

db.collect.insertMany(
    [<document 1>, <document 2>],
    {
        writeConcern: <document>,
        ordered: <boolean>
    }
)
Copy the code

Ordered Indicates whether the document was ordered. This is optional. The default value is true.

Insert two article sets into MongoDB’s YTAO database

db.article.insertMany(
    [
    {
        title: "Sticky/Unpack handling in Netty",
        url: "https://ytao.top/2019/12/09/10-netty/",
        author: "ytao"
    },
    {
        title: "WebSocket enables Instant Messaging on the Web",
        url: "https://ytao.top/2019/11/17/7_websocket/",
        author: "ytao"}])Copy the code

Inserted data

Similarly, insertOne() repeats the insert of an existing _ID, otherwise an error is reported.

insert

Insert () can insert single or multiple documents, and is the most common method, with the syntax

db.collect.insert(
    <document> or [<document 1>, <document 2>],
    {
        writeConcern: <document>,
        ordered: <boolean>
    }
)
Copy the code

If a single document is inserted, it is similar to insertOne(). If multiple documents are inserted, it is similar to insertMany(). The arguments writeConcern and ordered are the same.

save

Save () can also be used for data insertion. If the newly inserted _id exists, the existing document will be overwritten; if the _id does not exist, it will be inserted like insertOne(). Its operation syntax:

db.collect.save(
    <document>,
    {
        writeConcern: <document>
    }
)
Copy the code

update

Update methods are ** updateOne(), updateMany(), update(), replaceOne(), and save() **. Update () includes updateOne() and updateMany().

update

Update () allows you to update one or more documents with the syntax:

db.collection.update(
    <query>,
    <update>,
    {
        upsert: <boolean>,
        multi: <boolean>,
        writeConcern <document>,
        collation: <document>,
        arrayFilters: [<filter1>,<filter2>]
    }
)
Copy the code

Update parameters:

  • Query: The query criteria to update the document
  • Update: Field to be updated
  • Upsert: The default is false. When set to true, the update condition is inserted if the update condition does not match the data. Otherwise, if it is set to false, it will not be inserted.
  • Multi: The default value is false. If the value is set to True, all matched data is updated. If set to false, the first matched data is updated.
  • WriteConcern: the same argument as insert above.
  • Collation: Updates the collation rules of data.
  • ArrayFilters: Updates a specific element of array format data in the data.

I’ll show you two examples, a normal update and an update with arrayFilters data, which is a little harder to explain, but easier to understand by example.

Data before update:

{
    "_id" : ObjectId("5ed299cee89845fb9ec805e4"),
    "title" : "WebSocket enables Instant Messaging on the Web"."url" : "https://ytao.top/2019/11/17/7_websocket/"."author" : "ytao"
}
Copy the code

Case 1 update author data to [” Yang Tao “, “ytao”]

db.article.update(
    {title: "WebSocket enables Instant Messaging on the Web"},
    {$set: {author: ["Yang Tao"."ytao"]}})Copy the code

In case 2, YangTao of author data [” YangTao “, “ytao”] was updated to YangTao

db.article.update(
    {title: "WebSocket enables Instant Messaging on the Web"},
    {$set: {"author.$[idx]": "YangTao"}},
    {
        arrayFilters:[
            {"idx": {$eq: "Yang Tao"}}}])Copy the code

The above idx represents the position of the elements in the array.

Updated data

updateOne

UpdateOne () can only update one document, just like update(), which sets multi to false.

Grammar:

db.collection.updateOne( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ] , hint: <document|string> } )Copy the code

Hint is a new parameter in version 4.2.1 that specifies the index to update the document.

updateMany

UpdateMany () is used in the same way as update() to update multiple documents.

Grammar:

db.collection.updateMany( <filter>, <update>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ] , hint: <document|string> } )Copy the code

replaceOne

ReplaceOne completely overwrites a document without specifying an ID. Only one document can be overwritten.

Grammar:

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     hint: <document|string> 
   }
)
Copy the code

save

Save () overwrites the document by specifying the _id in the update. That is the use of save() inserted above.

delete

The methods for deleting a document are deleteOne(), deleteMany(), remove()

deleteOne

DeleteOne () can delete only one document at a time, with the syntax:

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)
Copy the code

Filter indicates the filter criteria for deleting a document.

deleteMany

DeleteMany () deletes multiple matched documents at once.

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)
Copy the code

remove

Remove () is to delete the queried document, and its syntax has two:

db.collection.remove(
   <query>,
   <justOne>
)
Copy the code

or

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

The justOne parameter is false by default, indicating that all matched data is deleted. True deletes only the first document

The query

Basic queries commonly used in MongoDB are ** findOne() ** and ** find() **.

findOne

FindOne () returns only the first matched document with the syntax:

db.collection.findOne(
    <query>, 
    <projection>

)
Copy the code

Parameter Description:

  • Query Indicates the query condition.
  • Projection represents the returned Field.

Let’s query a document and return only the title and URL

By specifying the value of a field as 1, the field is returned after the query.

find

Find () returns a set of matches. The syntax is:

db.collection.find(
    <query>, 
    <projection>

)
Copy the code

The following case query results:

conclusion

This article has carried on the simple understanding to the MongoDB entry and the basic operation, in this use process, a bit similar to the relational database operation shadow, so to have relational database use experience, get started is relatively simple.

More use of operation, the official document: docs.mongodb.com/manual/refe…

Recommended reading

ElasticSearch Installation and Basic Operation API

Redis5 new feature Streams for message queuing

MySQL master-slave replication based on Docker

Wait/Notify for Java Thread Communication




Follow the public account “Ytao”

Adhere to original technical article output, focusing on but not limited to Java related technology.