在SpringBoot中使用MongoDB完成數(shù)據(jù)存儲(chǔ)
我們?cè)陂_(kāi)發(fā)中用到的數(shù)據(jù)存儲(chǔ)工具有許多種,我們常見(jiàn)的數(shù)據(jù)存儲(chǔ)工具包括:
關(guān)系性數(shù)據(jù)庫(kù):使用表格來(lái)存儲(chǔ)數(shù)據(jù),支持事務(wù)和索引。(如:MySQL,Oracle,SQL Server等)。NoSQL數(shù)據(jù)庫(kù):不使用表格來(lái)存儲(chǔ)數(shù)據(jù),而是使用鍵值對(duì)、文檔、或者圖形等方式來(lái)存儲(chǔ)數(shù)據(jù),適合處理高并發(fā)和大規(guī)模數(shù)據(jù)。(Redis,MongoDB,Cassandra等)文件存儲(chǔ):將數(shù)據(jù)存儲(chǔ)在本地或者遠(yuǎn)程服務(wù)器文件中,常用與存儲(chǔ)較小的文件。(FTP,SFTP,AWS C3等)云存儲(chǔ):數(shù)據(jù)存儲(chǔ)在云端,方便多人協(xié)作和備份。(Google Drive,Dropbox,OneDriver等)內(nèi)存存儲(chǔ) :將數(shù)據(jù)存儲(chǔ)在內(nèi)存中,提供快速的讀寫速度,但是不適用存儲(chǔ)持久化數(shù)據(jù)(Redis,Memcache等)。緩存:將數(shù)據(jù)存儲(chǔ)在緩存中,提高訪問(wèn)速度,減少數(shù)據(jù)庫(kù)壓力。(Apc,Memcache,Redis等)隊(duì)列:將任務(wù)分發(fā)到不同的隊(duì)列中進(jìn)行處理,提高系統(tǒng)的可靠性和可拓展性。(RabbitMQ,Kafka等)
這篇我們將圍繞MongoDB進(jìn)行,MongoDB是一個(gè)開(kāi)源的,面向文檔的NoSQL數(shù)據(jù)庫(kù)管理系統(tǒng),使用類似JSON的BSON(二進(jìn)制JSON)格式來(lái)存儲(chǔ)數(shù)據(jù),具有靈活的數(shù)據(jù)模型和強(qiáng)大的查詢功能。
與傳統(tǒng)的關(guān)系型數(shù)據(jù)庫(kù)不同的是,MongoDB不使用表和行的結(jié)構(gòu),而是使用集合和文檔進(jìn)行的,一個(gè)集合就相當(dāng)于關(guān)系型數(shù)據(jù)庫(kù)里邊的表,一個(gè)文檔就相當(dāng)于表中的一行數(shù)據(jù),每個(gè)文檔都是一個(gè)鍵值對(duì)的集合,可以包含不同類型的數(shù)據(jù)。
MongoDB的特點(diǎn):
- 面向文檔:MongoDB使用靈活的文檔模型,可以存儲(chǔ)不同結(jié)構(gòu)的數(shù)據(jù),無(wú)需事先定義表結(jié)構(gòu)。
- 可擴(kuò)展性:MongoDB支持水平擴(kuò)展,可以通過(guò)添加更多的服務(wù)器來(lái)處理大規(guī)模的數(shù)據(jù)和高并發(fā)訪問(wèn)。
- 高性能:MongoDB具有快速的讀寫性能,支持索引和復(fù)雜查詢。
- 強(qiáng)大的查詢語(yǔ)言:MongoDB支持豐富的查詢語(yǔ)言,包括條件查詢、范圍查詢、正則表達(dá)式查詢等。
- 數(shù)據(jù)復(fù)制和故障恢復(fù):MongoDB支持?jǐn)?shù)據(jù)復(fù)制和自動(dòng)故障恢復(fù),可以提供高可用性和數(shù)據(jù)安全性。
- 地理空間索引:MongoDB支持地理空間索引,可以進(jìn)行地理位置相關(guān)的查詢和分析。
- 開(kāi)源和活躍的社區(qū):MongoDB是開(kāi)源的,擁有龐大的用戶社區(qū)和活躍的開(kāi)發(fā)者社區(qū)。
首先在我們測(cè)試MongoDB之前,我們需要安裝MongoDB,MongoDB下載網(wǎng)站:https://www.mongodb.com/try/download/community
之后安裝后,創(chuàng)建一個(gè)test數(shù)據(jù)庫(kù):
引入相關(guān)依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
在application.properties中配置相關(guān)連接:
spring.data.mongodb.uri=mongodb://localhost:27017/test server.port=7723
創(chuàng)建一個(gè)實(shí)體類User
public class User { @Id private Long id; private String username; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User() { } public User(Long id, String username, Integer age) { this.id = id; this.username = username; this.age = age; } }
實(shí)現(xiàn)用戶實(shí)體User的數(shù)據(jù)訪問(wèn)對(duì)象
public interface UserRepository extends MongoRepository<User, Long> { User findByUsername(String username); }
接下來(lái)創(chuàng)建一個(gè)單元測(cè)試用例:
@SpringBootTest(classes = Application.class) public class ApplicationTests { @Autowired private UserRepository userRepository; @Test public void test() throws Exception { userRepository.deleteAll(); // 創(chuàng)建三個(gè)User,并驗(yàn)證User總數(shù) userRepository.save(new User(1L, "麻衣**", 22)); userRepository.save(new User(2L, "娜*", 24)); userRepository.save(new User(3L, "玩偶**", 26)); Assertions.assertEquals(3, userRepository.findAll().size()); // 刪除一個(gè)User,再驗(yàn)證User總數(shù) User u = userRepository.findById(1L).get(); userRepository.delete(u); Assertions.assertEquals(2, userRepository.findAll().size()); // 刪除一個(gè)User,再驗(yàn)證User總數(shù) u = userRepository.findByUsername("娜*"); userRepository.delete(u); Assertions.assertEquals(1, userRepository.findAll().size()); } }
控制臺(tái)輸出
2023-11-17 15:39:39.655 INFO 15808 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'} 2023-11-17 15:39:39.737 INFO 15808 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:26}] to localhost:27017 2023-11-17 15:39:39.737 INFO 15808 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:27}] to localhost:27017 2023-11-17 15:39:39.737 INFO 15808 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=58204100} 2023-11-17 15:39:39.963 INFO 15808 --- [ main] c.miaow.demo.ApplicationTests : Started ApplicationTests in 2.079 seconds (JVM running for 2.619) 2023-11-17 15:39:40.106 INFO 15808 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:28}] to localhost:27017 2023-11-17 15:39:40.184 INFO 15808 --- [extShutdownHook] org.mongodb.driver.connection : Closed connection [connectionId{localValue:3, serverValue:28}] to localhost:27017 because the pool has been closed. 2023-11-17 15:39:40.184 INFO 15808 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
注意,MongoDB的語(yǔ)法有所區(qū)別,具體的如下:
查詢語(yǔ)法:
插入文檔:db.collection.insertOne(document)
或 db.collection.insertMany(documents)
查詢文檔:db.collection.find(query, projection)
更新文檔:db.collection.updateOne(filter, update)
或 db.collection.updateMany(filter, update)
刪除文檔:db.collection.deleteOne(filter)
或db.collection.deleteMany(filter)
條件查詢:db.collection.find({ field: value })
范圍查詢:db.collection.find({ field: { $gt: value1, $lt: value2 } })
正則表達(dá)式查詢:db.collection.find({ field: /pattern/ })
排序:db.collection.find().sort({ field: 1 })
(1表示升序,-1表示降序)
分頁(yè):db.collection.find().skip(offset).limit(limit)
聚合查詢:db.collection.aggregate(pipeline)
在Java中的相關(guān)操作:
連接MongoDB:使用MongoClient
類來(lái)連接MongoDB數(shù)據(jù)庫(kù)。
普通連接方式,如果是Spring Boot中就是配置一下
MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydatabase");
獲取集合:使用getCollection
方法獲取集合對(duì)象。
MongoCollection<Document> collection = database.getCollection("mycollection");
插入文檔:
Document document = new Document("name", "miaow") .append("age", 24) .append("email", "miaow@example.com"); collection.insertOne(document);
查詢文檔:
FindIterable<Document> result = collection.find(new Document("name", "miaow")); for (Document document : result) { // 處理查詢結(jié)果 }
更新文檔:
collection.updateOne(eq("name", "miaow"), new Document("$set", new Document("age", 24)));
刪除文檔:
collection.deleteOne(eq("name", "miaow"));
以上就是在SpringBoot中使用MongoDB完成數(shù)據(jù)存儲(chǔ)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot MongoDB數(shù)據(jù)存儲(chǔ)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
mybatis創(chuàng)建項(xiàng)目報(bào)Invalid?bound?statement?(not?found)錯(cuò)誤解決方法
使用MyBatis能夠幫助我們將SQL語(yǔ)句和Java代碼分離,這篇文章主要給大家介紹了關(guān)于mybatis創(chuàng)建項(xiàng)目報(bào)Invalid?bound?statement?(not?found)錯(cuò)誤的解決方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05tomcat報(bào)錯(cuò):Wrapper cannot find servlet class ...問(wèn)題解決
這篇文章主要介紹了tomcat報(bào)錯(cuò):Wrapper cannot find servlet class ...問(wèn)題解決的相關(guān)資料,需要的朋友可以參考下2016-11-11阿里面試Nacos配置中心交互模型是push還是pull原理解析
這篇文章主要為大家介紹了阿里面試Nacos配置中心交互模型是push還是pull原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07