Quickly learn about MongoDB and java to connect to MongoDB database

database structure

A mongo database can contain multiple sub-libraries (same as mysql), a sub-library can contain multiple collections, and each collection can store multiple documents. The document requirement must be the text content in json format, and there can only be one json in a document, so the document is regarded as the smallest data unit of the database, which can be regarded as a piece of data. Indexes can be added to collections to speed up queries on documents. Similarly, mongo databases are also classified as non-relational databases because of their storage characteristics based on json documents rather than tables.

Each document must have a unique id field. If it is not specified when writing a new document, the field will be automatically generated in the first level of json _idas the primary key id of the document.

The mongo database has the characteristics similar to a cache database. There is no need to create a database and collection in advance. When you write a collection into a database, if the database does not exist, it will be created automatically. Similarly, when writing a document, if the collection does not exist, it will be created automatically. An expiration time can also be added to each document to realize the function of automatically cleaning up the historical database. Therefore, with its excellent performance, mongo is sometimes used directly as a cache database.

Install the database: slightly, there are many similar tutorials on the Internet.

Command to connect to database in linux server (without password): ./mongo host:port
Command to connect to database cluster in linux server (without password): ./mongo host1:port1,host2:port2(multiple machines are connected with commas)
Command to connect to database in linux server (with password): ./mongo host:port/dbName -u username -p 'password'
Command to connect to database cluster in linux server (with password): ./mongo host1:port1,host2:port2/dbName -u username -p 'password'(connect multiple machines with commas)
Note: ./mongo here is the executable file used to connect to the database under the bin folder in the installation folder after the database is installed

Quickly view and understand a database

Query all databases:show dbs

Query all collections:show collections

Query all documents in the collection db.集合名称.find().pretty()
Note: In some versions, if there are too many documents in the collection, only some documents will be returned. The pretty() method is used to display all documents in a formatted manner for easy viewing.

Query some documents in the collection db.集合名称.find().limit(查询数量)
Note: If there are too many documents in the collection, it is recommended to use this method to avoid freezing the entire database.

Count the number of documents in the collectiondb.集合名称.find().count()

database query

Since the mongo database is a non-relational type, it means that its query will be very dependent on the index. If the json field of the query condition is not indexed, mongo will load all the documents of the collection into the memory for traversal. In the case of a large number of documents, it will easily overwhelm the memory and cause the database to crash.

The query condition of mongo is also a string of json, so it should be noted that the string needs to be quoted.

For specific query methods, please refer to the rookie tutorial

Add a query condition not mentioned in the rookie tutorial
to query documents that do not contain a certain fielddb.集合名称.find( { "指定字段": {$exists: false } } )

Java connect to mongoDb database

First, maven introduces dependencies

<!-- mongoDb 数据库依赖 -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.12.11</version>
</dependency>

The official document of java connection database

Connect to the database

// 引入的类
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

// 连接数据库代码片段
public void connect(MongoDb db)
{
    
    
	// MongoDb 类是我自己打包的一个类,主要用于存储连接数据库需要的 机器地址 端口号等信息
    String connectStr;
    if (db.getUser() == null) // 不带密码
        connectStr = "mongodb://" + db.getHost() + ":" + db.getPort() + "/" + db.getUserDb();
    else // 带有用户名和密码的
        connectStr = "mongodb://" + db.getUser() + ":" + db.getPassword() + "@"
                + db.getHost() + ":" + db.getPort() + "/" + db.getUserDb();
    MongoClient client = MongoClients.create(connectStr);
    MongoDatabase database = client.getDatabase(db.getDatabase());
}

Inquire

/**
 * 查询当前数据库中的所有集合
 */
public Set<String> showCollections()
{
    
    
	// db 是连接数据库代码中获取的 MongoDatabase 类
    if (db == null)
        throw new RuntimeException("not use database.");
    MongoIterable<String> mongoIterable = db.listCollectionNames();
    Set<String> set = new HashSet<>();
    for (String name : mongoIterable)
        set.add(name);
    return set;
}

Regarding the query conditions, there are detailed introductions in the document. Here is an example: If
you need to know more, you can click to jump to the document: set up query conditions , set up sorting conditions .

Bson query1 = Filters.lte("abc", 123); // 查询 abc 的值小于等于 123 的所有文档
Bson sort1 = Sorts.descending("abc"); // 以abc字段做降序排序
// db 是连接数据库代码中获取的 MongoDatabase 类
Document doc = db.getCollection("要查找的集合名称").find(query1).sort(sort1).first(); // 查找第一个文档

insert and delete

// db 是连接数据库代码中获取的 MongoDatabase 类
String collection = "要修改的集合名称";
// 插入一个文档
Document doc1 = new Document();
doc1.put("abc", 112);
db.getCollection(collection).insertOne(doc1);
// 删除 abc 的值小于等于 123 的所有文档
Bson query1 = Filters.lte("abc", 123);
db.getCollection(collection).deleteMany(query1);

Guess you like

Origin blog.csdn.net/weixin_44927769/article/details/126278645