What can mogodb do

What is MongoDB? What can I do?

1. What is MongoDB?
2. Why use MongoDB?
3. Main features
4. C/S service model
5. Perfect command line tools
6. Several shell practical operations
7. Use MongoDB in Java


1. What is MongoDB? MongoDB is a database management system designed for web applications and Internet infrastructure. Yes, MongoDB is a database, a NoSQL database

2. Why use MongoDB?
(1) MongoDB proposes the concept of documents and collections. It uses BSON (JSON-like) as its data model structure. Its structure is object-oriented rather than a two-dimensional table. It is like this in MongoDB to store a user.

{ username:'123', password:'123' } Using this data model enables MongoDB to provide high read and write capabilities in a production environment, and the throughput is greatly enhanced compared to SQL databases such as mysql.



(2) Easy to scale, automatic failover. Easy scalability refers to the provision of sharding capabilities, the ability to shard a data set, and the data storage pressure to be shared among multiple servers. Automatic failover is the concept of a replica set. MongoDB can detect whether the master node is alive, and when inactive, it can automatically promote the slave node to the master node to achieve failover.

(3) Because the data model is object-oriented, it can express rich and hierarchical data structures. For example, in a blog system, "comments" can be directly added to the "article" document, instead of creating three sheets like myqsl Table to describe this relationship.

3. Main features
(1) The
SQL database of the document data type is normalized, and the integrity and uniqueness of the data can be guaranteed through the constraints of the primary key or foreign key. Therefore, the SQL type database is often used for data integrity. system. MongoDB is inferior to SQL-type databases in this respect, and MongoDB does not have a fixed Schema. It is precisely because MongoDB has fewer such constraints, which can make the data storage structure more flexible and the storage speed faster.

(2) Instant query ability
MongoDB retains the ability to query relational databases in real time, and retains the ability to index (the bottom layer is based on B tree). This draws on the advantages of relational databases. Compared with the same type of NoSQL redis, it does not have the above capabilities.

(3) Replication capability
MongoDB itself provides a replica set that can distribute data on multiple machines to achieve redundancy, the purpose is to provide automatic failover and expand read capabilities.

(4) Speed ​​and Persistence The
MongoDB driver implements a write semantic fire and forget, that is, when the driver calls to write, you can immediately get a successful result (even if it is an error), so that the writing speed is faster. Of course, there will be a certain degree of insecurity, which is completely dependent on the network.

MongoDB provides the concept of Journaling log. In fact, it is like mysql's bin-log log. When it needs to be inserted, it will write records into the log first, and then complete the actual data operation. In this way, if there is a power outage, the process is suddenly interrupted. You can ensure that the data will not be wrong, and you can read the Journaling log to repair it through the repair function.

(5) Data expansion
MongoDB uses fragmentation technology to expand data. MongoDB can automatically fragment and transfer data blocks in fragments, so that the data stored in each server is of the same size.

4. The C/S service model
MongoDB core server is mainly started through the mongod program, and there is no need to configure the memory used by MongoDB at startup, because the design philosophy is that memory management is best given to the operating system, and there is a lack of memory configuration It is the design highlight of MongoDB. In addition, the fragmentation function can also be used through the mongos routing server.

The main client of MongoDB is the interactive js shell. Started by mongo, you can use js to directly communicate with MongoDB using js shell. Use js syntax to query MongoDB data like sql statement to query mysql data. In addition, various languages ​​are also provided. The driver package facilitates the access of various languages.

5. Complete command line tools
mongodump and mongorestore, standard tools for backing up and restoring databases. Export the BSON format and migrate the database.

mongoexport and mongoimport are used to import and export JSON, CSV and TSV data, useful when the data needs to support multiple formats. mongoimport can also be used for the initial import of large data sets, but by the way, you should also pay attention to it before importing. In order to make full use of mongoDB, you usually need to make some adjustments to the data model.

mongosniff, a network sniffing tool, used to observe the operations sent to the database. Basically, the BSON transmitted on the network is converted into a shell statement that is easy for people to read.

Therefore, it can be concluded that MongoDB combines the best features of key-value storage and relational databases. Because it is simple, the data is extremely fast, and it is relatively easy to scale a database that also provides a complex query mechanism. MongoDB needs to run on a 64-bit server, and it is best to deploy it separately. Because it is a database, it also needs to be processed in hot and cold standby.

6. Several shell operations.
Because this article is not an API manual, all the use of the shell here is also a basic introduction to what functions can be used and what statements, mainly to show the convenience of using the MongoDB shell, if you need to know the specific MongoDB shell The grammar can be found in the official documentation.

1. Switching the database
Use dba to
create a database is not a necessary operation. Databases and collections are created only when a document is inserted for the first time, which is consistent with the dynamic processing of data. Simplifies and speeds up the development process, and facilitates the dynamic allocation of namespaces. If you are worried about the database or collection being created accidentally, you can turn on strict mode

2. Insert syntax
1db.users.insert({username:"smith"})
2db.users.save({username:"smith"})
3. Find syntax
1 db.users.find()
2 db.users.count ()
4. Update syntax
1 db.users.update({username:"smith"},{ KaTeX parse error: Expected'EOF', got'}' at position 23: …untry:"Canada"}}̲) 2 // Remove the user name smi... unset:{country:1}}) 5 //Remove the country field of the user whose user name is smith 6 7 db.users.update({username:“jones”},{ KaTeX parse error: Expected'EOF', got'}' at position 48: …nce","rocky"]}}} ̲) 8 //Here is mainly multi-value... addToSet:{favorites.movies:"the maltese" )),false,true) 11 //Multiple updates 5. Delete syntax 1db.foo.remove() //Remove all data 2db.foo.remove((favorties.cities:"Cheyene"}) //Delete according to conditions







3db.drop() //Delete the entire collection
6. Index related syntax
1db.numbers.ensureIndex((num:1))
2//Create an ascending index
3db.numbers.getIndexes()
4//Get all indexes
7. Basic Management syntax
1 show dbs
2 //Query all databases
3 show collections
4 //Display all tables
5 db.stats()
6 //Display database status information
7 db.numbers.stats()
8 //Display collection table status information
9 db,shutdownServer()
10 //Stop the database
11 db.help()
12 //Get database operation commands
13 db.foo.help()
14 //Get table operation commands
15 tab key//It can automatically help us complete commands
The above commands are just simple examples. If you have not learned any database syntax before, and you start to learn SQL query syntax and MongoDB query syntax at the same time, which one will you find simpler? If you use a java driver to operate MongoDB, you will find that any query is the same as the query provided by Hibernate. As long as a query condition object is constructed, you can easily query (an example will be given next), blogger I was familiar with ES6 before, so it was no problem to start with MongoDB js shell. Because of this simple and perfect query mechanism, I fell in love with MongoDB deeply.

7. Use MongoDB in Java
1. Use maven to import the jar package.
The latest driver package is quoted here, which provides a new set of access and connection methods.

1
2 org.mongodb
3 mongodb-driver-sync
4 3.8.0-beta3
5
2、创建一个访问客户端
1 MongoClient client = MongoClients.create(“mongodb://10.201.76.94:27017”);
3、获取集合数量
1 public long count() {
2 MongoClient client = this.getClient();
3 MongoCollection collections= client.getDatabase(“mongodb_db_name”).getCollection(“mongodb_collection_name”);
4 return collections.count();
5 }
4、查询集合
1public List find(Document params,Bson sort,int skip,int limit) {
2 MongoClient client = this.getClient();
3 MongoCollection collections= client.getDatabase(“mongodb_db_name”).getCollection(“mongodb_collection_name”);
4 List list = new ArrayList(Integer.valueOf(config.getPro(“sync_limit”)));
5 collections.find(params).sort(sort).skip(skip).limit(limit).forEach(new Block( ) { 6 @Override 7 public void apply(Document document) { 8 list.add(document); 9} 10 }); 11 return list; 12 } Here only examples of simple links and simple MongoDB operations, you can see the operations The ease. When using the driver, it communicates with MongoDB based on a TCP socket. If there are too many query results that just happen to not be put into the first server, a getmore command will be sent to the server to obtain the next batch of query results.







When inserting data to the server, it will not wait for the server's response. The driver will assume that the write is successful, and actually use the client to generate the object id, but this behavior can be configured through configuration, which can be turned on through the safe mode, and the safe mode can be verified Error inserted on the server side.

Original address:
https://zhuanlan.zhihu.com/p/59753955

Guess you like

Origin blog.csdn.net/qq_44783283/article/details/108136918