java connects to MongoDB and performs operations

1. Java connection to MongoDB

        1. Import the MongoDB driver package

                 1.1jar package download address:

                        mongoDB jar package

         2. Get the connection object

//连接到 mongoDB 服务
MongoClient mc = new MongoClient("localhost",27017);

"localhost"         here represents the connected server address, and 27017 is the port number. The server address and port number can be omitted. The system default server address is "localhost" and the port number is 27017 .

        3. Close the connection

mc.close();

 2. View the library and view the collection

        1. Obtain the library through the connection object

//通过连接对象获取了库对象
MongoDatabase md = mc.getDatabase("myschool");

"myschool"         here represents the database name. If the specified database does not exist, mongoDB will create the database when you insert the document for the first time.

        2. View the collection

        To perform CRUD operations on data, you must first obtain the collection of operations.

//通过库对象获取表对象
MongoCollection<Document> collection = md.getCollection("student");
//全查
//文档的集合
FindIterable<Document> find = collection.find();
//迭代器对象 Cursor游标 
MongoCursor<Document> iterator = find.iterator();
while(iterator.hasNext()) {
	Document next = iterator.next();
	System.out.println(next);
}

        Use the find() method of the MongoCollection object, which has multiple overloaded methods. You can use the find() method without parameters to query all documents in the collection, or you can pass a Bson type filter to query documents that meet the conditions. . These overloaded methods all return an object of FindIterable type , through which all queried documents can be traversed.

Guess you like

Origin blog.csdn.net/m0_70314224/article/details/125830491