本文主要介绍通过java使用mongodb的基本语法与一些使用上的介绍
一. Terminologies
先来回顾一些mongodb的一些专业术语和关系型数据之间的关系
Let's see the analogies between Mongo and a traditional MySQL system:
-
Table in MySQL becomes a Collection in Mongo
-
Row becomes a Document
-
Column becomes a Field
-
Joins are defined as linking and embedded documents
This is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.
Now, let's dive into implementation to understand this powerful database.
二. Maven Dependencies
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.8.2</version>
</dependency>
To check if any new version of the library has been released – track the releases here.
三. Using MongoDB
我们先来了解一些基础的操作,然后进行一些说明。
1.连接mongodb
With version >= 2.10.0, we'll use the MongoClient:
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
//或者默认的就会连接本地数据库
MongoClient mongoClient = MongoClients.create();
//或者对于需要验证的url可以直接
MongoClient mongoClient = MongoClients.create("mongodb://userName:password@ip:port/databaseName?authSource=admin");
2. 数据库创建、获取与遍历
有意思的是,如果没有数据库,javaclient将会创建一个数据库
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
//展示目前存在的数据库
mongoClient.listDatabasesNames().forEach(System.out::println);
3. collection相关
创建一个collection
//创建一个Collection
database.createCollection("customers");
//展示此数据库下所拥有的Collection
database.listCollectionNames().forEach(System.out::println);
4. 文档相关操作
插入文档到Collection
MongoCollection<Document> collection = database.getCollection("customers");
Document document = new Document();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insertOne(document);
更新一个文档
//需要两个条件:查询要更新的文档、更新的内容
//query
Document query = new Document();
query.put("name", "Shubham");
//newDocument
Document newDocument = new Document();
newDocument.put("name", "John");
//使用set语法进行数据更新
Document updateObject = new Document();
updateObject.put("$set", newDocument);
//只更新一个符合条件的文档
collection.updateOne(query, updateObject);
条件遍历一个文档
//设置查询条件
Document searchQuery = new Document();
searchQuery.put("name", "John");
//遍历符合条件的文档
FindIterable<Document> cursor = collection.find(searchQuery);
try (final MongoCursor<Document> cursorIterator = cursor.cursor()) {
while (cursorIterator.hasNext()) {
System.out.println(cursorIterator.next());
}
}
删除一个文档
Document searchQuery = new Document();
searchQuery.put("name", "John");
//只删除一个符合条件的文档
collection.deleteOne(searchQuery);