SpringBoot系列之MongoCollection用法示例

Posted smileNicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot系列之MongoCollection用法示例相关的知识,希望对你有一定的参考价值。

1、前言

上一章的学习中,我们知道了Spring Data MongoDB的基本使用,本章节作为补充,介绍MongoCollection的基本使用

2、环境搭建

开发环境

  • JDK 1.8

  • SpringBoot2.2.1

  • Maven 3.2+

  • 开发工具

    • IntelliJ IDEA
    • smartGit
    • Navicat15

使用阿里云提供的脚手架快速创建项目:
https://start.aliyun.com/bootstrap.html

也可以在idea里,将这个链接复制到Spring Initializr这里,然后创建项目

jdk选择8的

选择spring data MongoDB


加上Junit测试配置,配合springboot的测试框架进行实验

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

非SpringBoot项目,需要自己加上配置:

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>3.0.4</version>
</dependency>

3、MongoCollection用法示例

数据进行初始化处理

    private static final String DATABASE = "test";
    private static final String COLLECTION = "user";
    private static final String USER_JSON = "/userjson.txt";
    private static MongoClient mongoClient;
    private static MongoDatabase mongoDatabase;
    private static MongoCollection<Document> collection;

    @BeforeClass
    public static void init() throws IOException 
        mongoClient = new MongoClient("127.0.0.1", 27017);
        mongoDatabase = mongoClient.getDatabase(DATABASE);
        collection = mongoDatabase.getCollection(COLLECTION);

        collection.drop();

        InputStream inputStream = MongodbAggregationTests.class.getResourceAsStream(USER_JSON);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        reader.lines()
                .forEach(l->collection.insertOne(Document.parse(l)));
        reader.close();
    

调用MongoCollection的基本操作:

@Test
    public void insertTest() 
        Document document = new Document("_id",10).
                append("name" , "User10").
                append("age",18).
                append("email","test10@qq.com");
        collection.insertOne(document);
    

    @Test
    public void insertManyTest() 
        collection.drop();
        List<Document> users = Stream.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L ,9L).map(i -> 
            Document user = new Document();
            user.append("_id",i);
            user.append("name" ,"User"+i);
            user.append("age" , 18);
            user.append("email", "test" + i + "@qq.com");
            return user;
        ).collect(Collectors.toList());
        collection.insertMany(users);
    

    @Test
    public void delTest() 
        Bson filter = Filters.eq("name" , "User1");
        collection.deleteOne(filter);
    

    @Test
    public void delManyTest() 
        Bson filter = Filters.eq("name" , "User1");
        collection.deleteMany(filter);
    

    @Test
    public void updateTest() 
        Bson filter = Filters.eq("name" , "User1");
        Document document = new Document("$set" , new Document("age" , 100));
        collection.updateOne(filter , document);
    

    @Test
    public void updateManyTest() 
        Bson filter = Filters.eq("name" , "User1");
        Document document = new Document("$set" , new Document("age" , 100));
        collection.updateMany(filter , document);
    

    @Test
    public void findAllTest() 
        FindIterable iterable = collection.find();
        MongoCursor cursor = iterable.cursor();
        while(cursor.hasNext()) 
            log.info("user:",cursor.next());
        
    

    @Test
    public void findConditionTest() 
        Bson filter = Filters.eq("name" , "User1");
        FindIterable iterable = collection.find(filter);
        MongoCursor cursor = iterable.cursor();
        while(cursor.hasNext()) 
            log.info("user:",cursor.next());
        
    

    @Test
    public void findFirstTest() 
        Document document = collection.find().first();
        log.info("user first :" , document);
    

Collection也可以从MongoTemplate获取 ,测试时候,需要加上@org.junit.jupiter.api.Test,不用Junit的test,同时类加上@SpringBootTest

	@Autowired
    private MongoTemplate mongoTemplate;
    
	@org.junit.jupiter.api.Test
    public void fromMongoTemplate() 
        collection = mongoTemplate.getCollection(COLLECTION);
        FindIterable<Document> iterable = collection.find();
        for (Document next : iterable) 
            log.info("user : " , next);
        
    

以上是关于SpringBoot系列之MongoCollection用法示例的主要内容,如果未能解决你的问题,请参考以下文章

重学SpringBoot系列之基础知识回顾

SpringBoot系列之集成Dubbo的方式

SpringBoot系列之日志框架使用教程

SpringBoot系列之集成logback实现日志打印(篇二)

MP实战系列之集成springboot

Java之Spring Boot入门到精通IDEA版SpringBoot原理分析,SpringBoot监控(一篇文章精通系列)下