当前位置:网站首页>Mongondb API usage
Mongondb API usage
2022-07-26 05:24:00 【Monster in the North Sea】
mongodb-driver yes mongo Officially launched java Connect mongoDB Driver package , amount to JDBC drive . Let's use it now mongodb-driver Finish right Mongodb The operation of .
Add dependency , Pay attention to the version you use
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb‐driver</artifactId>
<version>3.10.1</version>
</dependency>
Test code
public class MongoTest {
// client
private MongoClient mongoClient;
// aggregate
private MongoCollection<Document> comment;
@Before
public void init() {
//1. Create operation MongoDB The client of
mongoClient = new MongoClient("192.168.200.128");
// MongoClient mongoClient = new MongoClient("192.168.200.128",27017);
//2. Select database use commentdb
MongoDatabase commentdb = mongoClient.getDatabase("commentdb");
//3. Get collection db.comment
comment = commentdb.getCollection("comment");
}
// Query all the data db.comment.find()
@Test
public void test1() {
//4. Use the set to query , Query all the data db.comment.find()
FindIterable<Document> documents = comment.find();
//5. Parse the result set ( Print )
// "_id" : "1", "content" : " Why did it go wrong ", "userid" : "1012", "thumbup" : 2020 }
for (Document document : documents) {
System.out.println("------------------------------");
System.out.println("_id:" + document.get("_id"));
System.out.println("content:" + document.get("content"));
System.out.println("userid:" + document.get("userid"));
System.out.println("thumbup:" + document.get("thumbup"));
}
}
@After
public void after() {
// Release resources , Close client
mongoClient.close();
}
// According to the condition _id Query data ,db.comment.find({"_id" : "1"})
@Test
public void test2() {
// Encapsulate query criteria , You can pass one Map aggregate , Conduct multi condition query
BasicDBObject bson = new BasicDBObject("_id", "1");
// Execute the query
FindIterable<Document> documents = comment.find(bson);
for (Document document : documents) {
System.out.println("------------------------------");
System.out.println("_id:" + document.get("_id"));
System.out.println("content:" + document.get("content"));
System.out.println("userid:" + document.get("userid"));
System.out.println("thumbup:" + document.get("thumbup"));
}
}
// newly added db.comment.insert({"_id" : "5", "content" : " perseverance prevails 123", "userid" : "1018", "thumbup" : 1212})
@Test
public void test3() {
// Encapsulate new data
Map<String, Object> map = new HashMap<>();
map.put("_id", "6");
map.put("content", " New test ");
map.put("userid", "1019");
map.put("thumbup", "666");
// Encapsulate new document objects
Document document = new Document(map);
// Execute new Add multiple :insertMany(List<Document>)
comment.insertOne(document);
}
// modify ,db.comment.update({"_id" : "5"},{$set:{"userid" : "888"}})
@Test
public void test4() {
// Create modified conditions
BasicDBObject filter = new BasicDBObject("_id", "6");
// Create modified values
BasicDBObject update = new BasicDBObject("$set", new Document("userid", "999"));
// Execute modification
comment.updateOne(filter, update);
}
// Delete ,db.comment.remove({"_id" : "5"})
@Test
public void test5() {
// Create a deleted condition
BasicDBObject bson = new BasicDBObject("_id", "6");
// Execution deletion
comment.deleteOne(bson);
}
}
Boot Use
yml To configure 
SpringData Inquire about
Persistence layer writing , Only need to integrate the specified interface , The frame will scan .
And what's more !!!!!!!!!!!!
SpringDataMongoDB, Support query definition by query method name
You just need to follow the rules , Specify method name !!! Framework helps you generate MongoDB Query statement !
But you must inherit this class ( Only for query statements !!!!!), also springData The framework also encapsulates some methods , You can use it directly !
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CommentRepository extends MongoRepository<Comment, String> {
//SpringDataMongoDB, Support query definition by query method name
// According to the article id Query article comment data
List<Comment> findByArticleid(String articleId);
// Query according to the release time and the number of likes
// List<Comment> findByPublishdateAndThumbup(Date date, Integer thumbup);
// According to the user id Inquire about , And sort in reverse order according to the release time
// List<Comment> findByUseridOrderbOrderByPublishdateDesc(String userid);
}
MongoRepository This and the interface provide some methods by default , Easy to use
Template classes use
private MongoTemplate mongoTemplate;
The above query uses SpringData Provided .
For some modification operations , Or is it only used through template classes .
Solve the problem of repeated likes
take user id And articles id As key , Store in redis in , Because I often read and write , therefore redis Higher performance !
Judge before each like operation .
At loading time , You can also load the corresponding likes , Set up for users at the front end The like button is not available
边栏推荐
- NetCore MySql The user specified as a definer (‘admin‘@‘%‘) does not exist
- Recommended reading: how can testers get familiar with new businesses quickly?
- Ansible中常用的模块
- DOM event flow event bubble event capture event delegate
- DOM操作--操作节点
- NPM operation instruction
- CMD operation command
- Embedded sharing collection 21
- Real scientific weight loss
- It's enough for newcomers to learn how to do functional tests
猜你喜欢
随机推荐
C语言函数
C language - Advanced pointer
35. Search the insertion position
SAP报表开发步骤
Earth system model (cesm) practical technology
Shell process control (emphasis), if judgment, case statement, let usage, for ((initial value; loop control condition; variable change)) and for variable in value 1 value 2 value 3..., while loop
Test of countlaunch demo
Attack and defense world flatscience
When AQS wakes up the thread, I understand why it traverses from the back to the front
Mathematical modeling and optimization analysis based on general optimization software gams
数仓搭建-DIM层
Recommended reading: how can testers get familiar with new businesses quickly?
SQL注入
Unity scene jump script
家居vr全景展示制作提高客户转化
kubernetes install completed
Webassembly 01 basic information
高频电子线路复习考试题及答案
Basic methods of realizing licensing function in C language
Full analysis of domain name resolution process means better text understanding









