gpt4 book ai didi

SpringBoot系列之MongoCollection用法示例

转载 作者:知者 更新时间:2024-03-13 08:21:42 24 4
gpt4 key购买 nike

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);
        }
    }

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com