JavaApi操作MongoDB
本文演示了,如何連線到MongoDB,如何選擇資料庫、表,進行查詢的操作。
pom檔案
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sunyuqi.mongodb</groupId>
<artifactId>java-mongodb</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
</project>
CURD操作
package com.sunyuqi.mongodb;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import java.util.function.Consumer;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;
public class TestMongoDB {
MongoCollection<Document> collection;
@Before
public void init() {
// 建立連線
MongoClient mongoClient = MongoClients.create("mongodb://192.168.130.128:27017");
// 選擇資料庫
MongoDatabase database = mongoClient.getDatabase("testdb");
// 選擇表
collection = database.getCollection("user");
}
// 查詢age<=50並且id>=100的使用者資訊,並且按照id倒序排序,只返回id,age欄位,不返回_id欄位
@Test
public void testQuery() {
this.collection.find(
and(
lte("age", 30),
gte("id", 100)
)
).sort(descending("id"))
.projection(fields(include("id", "age"),
excludeId()))
.forEach((Consumer<? super Document>) document -> {
System.out.println(document.toJson());
});
}
// 插入資料
@Test
public void testInsert(){
Document document = new Document();
document.append("id", 1000);
document.append("username", "張三");
document.append("age", 30);
this.collection.insertOne(document);
// 查詢該資料
this.collection.find(eq("id", 1000)).forEach((Consumer<? super Document>) document1 -> {
System.out.println(document1.toJson());
});
}
// 更新資料
@Test
public void testUpdate(){
UpdateResult updateResult = this.collection.updateOne(eq("id", 1000), Updates.set("age", 40));
System.out.println(updateResult);
// 查詢該資料
this.collection.find(eq("id", 1000)).forEach((Consumer<? super Document>) document1 -> {
System.out.println(document1.toJson());
});
}
// 刪除資料
@Test
public void testDelete(){
DeleteResult deleteResult = this.collection.deleteMany(eq("age", 25));
System.out.println(deleteResult);
}
}
物件導向操作
前面對MongoDB的操作都是基於Document物件操作,操作略顯繁瑣,下面我們通過物件導向的方式進行操作。 建立User、Address物件:
package com.sunyuqi.mongodb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bson.types.ObjectId;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private ObjectId id;
private String name;
private int age;
private Address address;
}
User中有一個欄位為Address,該類定義如下
package com.sunyuqi.mongodb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {
private String street;
private String city;
private String zip;
}
測試物件的CURD
package com.sunyuqi.mongodb;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.sunyuqi.mongodb.pojo.Address;
import com.sunyuqi.mongodb.pojo.User;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
public class TestUser {
MongoCollection<User> objectCollection;
@Before
public void init() {
//定義物件的解碼註冊器
CodecRegistry pojoCodecRegistry = CodecRegistries.
fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
// 建立連線
MongoClient mongoClient = MongoClients.create("mongodb://192.168.130.128:27017");
// 選擇資料庫 並且 註冊解碼器
MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb")
.withCodecRegistry(pojoCodecRegistry);
// 選擇表
this.objectCollection = mongoDatabase
.getCollection("user_detail", User.class);
}
// 插入一條
@Test
public void testInsert() {
User user = new User(ObjectId.get(), "張三", 21,new Address("人民路", "上海市", "123456"));
this.objectCollection.insertOne(user);
System.out.println("插入資料成功");
}
// 批量插入
@Test
public void testInserts() {
List<User> userList = Arrays.asList(
new User(ObjectId.get(), "張三", 20, new Address("上海北路", "上海市", "123456")),
new User(ObjectId.get(), "李四", 21, new Address("北京西路", "北京市", "222222")),
new User(ObjectId.get(), "王五", 22, new Address("南京東路", "南京市", "333333")),
new User(ObjectId.get(), "趙六", 23, new Address("陝西南路", "陝西市", "444444")),
new User(ObjectId.get(), "孫七", 24, new Address("南京西路", "南京市", "555555")));
this.objectCollection.insertMany(userList);
System.out.println("插入資料成功");
}
// 查詢
@Test
public void testQuery() {
this.objectCollection.find(eq("name", "張三"))
.forEach((Consumer<? super User>) user -> {
System.out.println(user);
});
}
// 更新
@Test
public void testUpdate() {
UpdateResult updateResult =
this.objectCollection.updateMany(eq("name", "張三"), set("age", 22));
System.out.println(updateResult);
}
// 刪除
@Test
public void testDelete() {
DeleteResult deleteResult =
this.objectCollection.deleteMany(eq("name", "張三"));
System.out.println(deleteResult);
}
}
相關文章
- JavaAPI操作MongoDB--基本增刪改查JavaAPIMongoDB
- mongoDB操作MongoDB
- MongoDB基本操作MongoDB
- PHP 操作 MongoDBPHPMongoDB
- Mongodb 管理操作MongoDB
- Go操作MongoDBMongoDB
- JavaAPI-工具類JavaAPI
- MongoDB基礎操作MongoDB
- 【mongoDB】常用操作命令MongoDB
- MongoDB相關操作MongoDB
- Kubernetes fabric8 JavaAPIJavaAPI
- SpringBoot 整合 Spring Data Mongodb 操作 MongoDB 詳解Spring BootMongoDB
- mongodb資料庫操作MongoDB資料庫
- mongodb聚合操作記錄MongoDB
- MongoDB 資料庫操作MongoDB資料庫
- MongoDB(7)- 文件插入操作MongoDB
- Mongodb-基礎操作MongoDB
- MongoDB的常用Query操作及操作符MongoDB
- SpringBoot實戰分析-MongoDB操作Spring BootMongoDB
- Spring Boot中快速操作MongodbSpring BootMongoDB
- spring-data-mongodb常用操作SpringMongoDB
- mongodb批量操作, bulk_write,MongoDB
- C#簡單操作MongoDBC#MongoDB
- MongoDB增刪改查操作MongoDB
- python操作mongodb資料庫PythonMongoDB資料庫
- MongoDB分片叢集常用操作MongoDB
- MongoDB學習之聚合操作MongoDB
- 0115 springboot template方式操作mongodbSpring BootMongoDB
- Elasticsearch入門及掌握其JavaAPIElasticsearchJavaAPI
- 【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(下)MongoDB筆記
- 【MongoDB學習筆記】-使用 MongoDB 進行 CRUD 操作(上)MongoDB筆記
- MongoDB 入門教程系列之三:使用 Restful API 操作 MongoDBMongoDBRESTAPI
- MongoDB 入門教程系列之二:使用 Spring Boot 操作 MongoDBMongoDBSpring Boot
- Python 資料庫騷操作 -- MongoDBPython資料庫MongoDB
- Python資料庫MongoDB騷操作Python資料庫MongoDB
- MongoDB 4.X CRUD基本操作MongoDB
- Python操作MongoDB文件資料庫PythonMongoDB資料庫
- PHP操作MongoDB(增刪改查)PHPMongoDB