当前位置:网站首页>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
 Insert picture description here

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 .
 Insert picture description here

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

原网站

版权声明
本文为[Monster in the North Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207260518160559.html