mongodb入门-3-Java中使用mongodb

2022/3/27 2:22:34

本文主要是介绍mongodb入门-3-Java中使用mongodb,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

无spring使用mongodb

导入依赖

版本我选择的是<mongo-driver-version>3.12.10</mongo-driver-version>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

API的简单使用

package com.twc;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;

import java.util.Random;

public class MongoJDBC {

    public static MongoDatabase getDataBase(String db){
        MongoClient client = new MongoClient("localhost", 27017);
        return client.getDatabase(db);
    }

    String dbName = "mydb";
    String collName = "c3";


    @Test
    public void testCreateCollection(){
        MongoDatabase dataBase = getDataBase(dbName);
        dataBase.createCollection(collName);
    }

    @Test
    public void testInsert(){
        MongoDatabase dataBase = getDataBase(dbName);
        MongoCollection<Document> coll = dataBase.getCollection(collName);
        for (int i = 0; i < 100; i++) {
            coll.insertOne(new Document("name", "name" + new Random().nextInt(10000))
                    .append("age", 15 + new Random().nextInt(40))
                    .append("gender", new Random().nextBoolean() ? "female" : "male"));
        }
    }

    @Test
    public void testFind(){
        MongoDatabase dataBase = getDataBase(dbName);
        MongoCollection<Document> coll = dataBase.getCollection(collName);

        printAll(coll);
    }

    @Test
    public void updateMany(){
        MongoDatabase dataBase = getDataBase(dbName);
        MongoCollection<Document> coll = dataBase.getCollection(collName);

        //将18以上的标记为成年,以下的为未成年
        Bson gte18 = Filters.gte("age", 18);
        coll.updateMany(gte18, new Document("$set", new Document("adult", true)));

        //将18以上的标记为成年,以下的为未成年
        Bson lt18 = Filters.lt("age", 18);
        coll.updateMany(lt18, new Document("$set", new Document("adult", false)));

        printAll(coll);

        System.out.println("-----DeleteMany");
        coll.deleteMany(Filters.eq("gender", "female"));

        printAll(coll);
    }

    private void printAll(MongoCollection<Document> coll) {
        FindIterable<Document> documents = coll.find();
        for (Document document : documents) {
            System.out.println(document);
        }
    }

}

springboot使用mongodb



这篇关于mongodb入门-3-Java中使用mongodb的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程