Basic concepts and basic command usage of MongoDB

Posted by dragonfly4 on Fri, 28 Jan 2022 00:03:38 +0100

1, MongoDB concept

1. Using business application scenarios

The specific application scenarios are as follows:

1) In social scenes, MongoDB is used to store user information and circle of friends information published by users, and the functions of nearby people and places are realized through geographical location index.

2) In the game scene, MongoDB is used to store the game user information. The user's equipment and points are directly stored in the form of embedded documents, which is convenient for query, efficient storage and access.

3) In the logistics scenario, MongoDB is used to store the order information, and the order status will be updated continuously during the transportation process. It is stored in the form of MongoDB embedded array, which can be stored in one query

Read out all changes of the order.

4) In the Internet of things scenario, MongoDB is used to store the information of all connected intelligent devices and the log information reported by the devices, and conduct multi-dimensional analysis of these information.

5) Live video broadcasting, using MongoDB to store user information, like interactive information, etc.

2. Use scene selection

Applications do not need transaction and complex join support.

The application data model cannot be determined. I want to develop iteratively quickly.

QPS of application reading and writing is high.

Applications need big data level data storage.

Applications require a large number of geographic location queries and text queries (such as log storage).

3. Introduction

MongoDB is an open source, high-performance, schema free document database. It is the most non relational database like relational database (MySQL).

The data structure it supports is very loose. It is a format similar to JSON called BSON, so it can store complex data types and is quite flexible.

A record in MongoDB is a document, which is a data structure image composed of fields and value pairs (fifield:value), that is, a document is considered an object.

The data type of a field is character type. Its value can include other documents, ordinary arrays and document arrays in addition to some basic types.

It has the characteristics of high performance, high availability, high expansion and modeless structure

4. Architecture

By default, mongodb has three default libraries: admin, local and config

  • admin: This is the "root" database. If a user is added to this database, this user will automatically inherit the permissions of all databases. Some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server.
  • Local: this data will never be copied and can be used to store any collection limited to a single local server
  • Config: when Mongo is used for sharding settings, the config database is used internally to save sharding related information.

2, Basic command usage

1. Database operation

# Create / use database (if the database does not exist, create database dbame, otherwise switch to the specified database dbname)
use Database name(For example: use testdb)

# Query all libraries (new libraries will not be queried if no collection is created)
show dbs

# View the library for the current operation
db

# Delete Library
use Specific database name
db.dropDatabase()

2. Collection operation

Create Collection - display creation:

# Enter testdb database
use testdb
# Create collection
db.createCollection('name');

Query all sets:

show collections

Delete collection:
To demonstrate the deletion effect, create several more collections, as follows:

Use the delete method to delete the collection named test1. The command is as follows:

# db. Set name drop(), for example:
db.test1.drop()

effect:

3. Document operation

For the following operations, the database name is tsetdb and the collection name is test.

3.1.1. New document

New documents, multiple separated by commas [if the current set name does not exist, it will be created automatically]

Test content:

// articleid, content and userid are the field names in the document
    db.test.insert([{
        "articleid":"1",
        "content":"Test content 1",
        "userid":"1"
    },{
        "articleid":"2",
        "content":"Test content 2",
        "userid":"2"
    }]);

effect:

3.1.2. consult your documentation

Query all:

	db.test.find()


Query all - specify fields:
Query all data and return the specified field. It will be returned by default_ id field, 0 means no return

db.test.find({},{userid:1,content:1,_id:0})


Specify query - returns all fields of a document:

 db.test.findOne({userid:'1'})

Specify query - returns all fields of all documents:

db.test.find({userid:'1'})

Specify query - return specific fields:
Query all data with userid 1 and return the specified field. It will be returned by default_ id field, 0 means no return

db.test.find({userid:'1'},{userid:1,content:1,_id:0})

3.1.3. Update document

1. Overwrite update:
Only the updated fields will be retained in the document, and other fields will be deleted

db.test.update({userid:"1"},{content:"Modification content"});

effect:

2. Local update:
Through the $set instruction, only the modified fields are updated

db.test.update({userid:"2"},{$set:{content:"Local update content"}})


3. Batch update:
Whether the above-mentioned overlay update or local update will only match one piece of data, that is, when a piece of data that meets the requirements is updated, even if there is still data that meets the requirements, it will not be updated unless the update command is executed again. Obviously, this is unreasonable, so it needs to use batch update;

db.test.update({userid:"1"},{$set:{content:"Batch update"}},{multi:true})

4. Create update:
If the updated document value does not exist, insert the document to add

db.test.update({userid:"3"},{$set:{content:"Create update"}},{upsert:true})

effect:

3.1.4. remove document

Delete all documents:

db.test.remove({})

Delete documents by criteria:

# For example: delete the document data with userid 1
db.test.remove({userid:"1"})

3.1.5. Advanced query

1. Statistical query:

# {} indicates with condition
db.test.count() perhaps db.test.count({userid:'1'})

2. Paging query:
You can use the limit() method to read the specified amount of data and the skip() method to skip the specified amount of data

# On the first page, there are two items per page (subscript values are 0 and 1), so skip is 0
db.test.find().skip(0).limit(2)
# The second page (subscript values are 2 and 3), so skip is 2
db.test.find().skip(2).limit(2)

effect:

3. Sort query:
sort() method sorts the data. 1 is in ascending order and - 1 is in descending order

db.test.find().sort({userid:-1})

4. Paging sort query:
First sort(), then skip(), and finally the displayed limit()

db.test.find().skip(0).limit(2).sort({userid:-1})

5. Regular query:

# Field represents a field in the document
db.lhz.find({field:/regular expression /})

6. Comparison query:
Greater than - $gt, less than - $lt, greater than or equal to - $gte, less than or equal to - $lte, not equal to - $ne

# userid greater than 10
db.test.find({ "userid" : { $gt: 10 }})

7. Include query:
Include - $in, not - $nin

db.test.find({userid:{$in:["1","2"]}})

8. Multi criteria query:
And and or can be used in combination

# And query
db.test.find({$and:[{userid:"1"},{articleid:{$gt:1}}]})
# Or query
db.test.find({$or:[{userid:"2"},{articleid:{$lt:1}}]})

4. Command summary ★

Select switch database: use articledb
Insert data: dB comment. Insert ({bson data})
Query all data: dB comment. find();
Condition query data: dB comment. Find ({condition})
Query the first qualified record: dB comment. Findone ({condition})
Query the first few qualified records: dB comment. Find ({condition}) Limit (number)
Query qualified skipped records: dB comment. Find ({condition}) Skip (number)
Modify data:

db.comment.update({condition},{Modified data}) 
or	
db.comment.update({condition},{$set:{The field of the section to modify:data})

Modify data and add a field value: dB comment. Update ({condition}, {$inc: {self increasing field: step value}})
Delete data: dB comment. Remove ({condition})
Statistics query: dB comment. Count ({condition})
Fuzzy query: dB comment. Find ({field name: / regular expression /})
Conditional comparison operation: dB comment. Find ({field name: {$gt: value}})
Include query:

db.comment.find({Field name:{$in:[Value 1, value 2]}})  
or
db.comment.find({Field name:{$nin:[Value 1, value 2]}})

Conditional connection query:

db.comment.find({$and:[{Condition 1},{Condition 2}]}) 
or
db.comment.find({$or:[{Condition 1},{Condition 2}]})

Topics: Java Database MongoDB nosql