java 实现mongoDB 增加,删除,修改,查看,多条件查询,聚合查询,分组查询,多表关联查询(史上最全)

首先idea创建一手springboot项目 引入如下依赖

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

下面是具体的java对mongod的操作。

需要将

data = mongod.getDatabase("runoob");

获取的数据库换成自己的数据库,端口为默认端口

这里我写了一个

@BeforeEach
@AfterEach
两个注解:分别是在执行测试类之前执行和在测试类执行之后执行。我使用的是springboot2,如果是springboot1需要将这两个注解修改为
@Before
@After
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.UpdateOneModel;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.print.Doc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

@SpringBootTest
public class MongodJointTest {
    private MongoClient mongod;
    private MongoDatabase data;

    @BeforeEach
    public void mongoJoint() {
        mongod = new MongoClient("localhost", 27017);
        data = mongod.getDatabase("runoob");
    }

    @AfterEach
    public void closeMongo() {
        mongod.close();
    }


    //单条插入
    @Test
    public void insertMongo() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        Document c = new Document();
        c.append("title", "s标题qq");
        c.append("encode", 22.0);
        ab1.insertOne(c);
        System.out.println("数据插入成功");
    }

    //多条插入
    @Test
    public void insertManyMongo() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        Document c0 = new Document();
        c0.append("title", "标题0");
        c0.append("encode", 21.0);
        Document c1 = new Document();
        c1.append("title", "标题1");
        c1.append("encode", 22.0);
        Document c2 = new Document();
        c2.append("title", "标题2");
        c2.append("encode", 23.0);
        List<Document> c = Arrays.asList(c0, c1, c2);
        ab1.insertMany(c);
        System.out.println("数据插入成功");
    }

    //删除
    @Test
    public void delMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        Document c = new Document();
        c.append("title", "a");
        ab1.deleteOne(c);
        //两种写法
        //ab1.deleteOne(Filters.eq("title","b"));
    }

    //修改信息
    @Test
    public void upMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        ab1.updateOne(Filters.eq("title", "标题"), new Document("$set", new Document("encode", 21.0)));
    }

    //批量插入,修改,(也可删除)
    @Test
    public void sumMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        ab1.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document("title", "p标题1")),
                new InsertOneModel<>(new Document("title", "p标题2")),
                new InsertOneModel<>(new Document("title", "p标题3")),
                new UpdateOneModel<>(new Document("title", "p标题1"), new Document("$set", new Document("title", "p批量修改标题")))
        ));
    }

    //查询
    @Test
    public void sendMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> documents = ab1.find().limit(3).skip(2);
        for (Document doc : documents) {
            System.out.println(doc.get("_id") + "   " + doc.get("title") + "   " + doc.get("encode"));
        }
    }

    //排序
    @Test
    public void sendSortMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        Document c = new Document();
        //c.append("encode",1);
        c.append("encode", -1);
        FindIterable<Document> documents = ab1.find().sort(c);
        for (Document doc : documents) {
            System.out.println(doc.get("_id") + "   " + doc.get("title") + "   " + doc.get("encode"));
        }
    }

    //条件查询
    @Test
    public void conditionMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> d = ab1.find(Filters.lt("encode", 20));
//         FindIterable<Document> d = ab1.find(Filters.lte("encode",20));
//         FindIterable<Document> d = ab1.find(Filters.gt("encode",20));
//         FindIterable<Document> d = ab1.find(Filters.gte("encode",20));
//         FindIterable<Document> d = ab1.find(Filters.ne("encode",20));
        for (Document doc : d) {
            System.out.println(doc.get("_id") + "   " + doc.get("title") + "   " + doc.get("encode"));
        }
    }


    //条件查询
    @Test
    public void conditionMongod1() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        Bson where = Filters.and(Filters.gt("encode", 20), Filters.eq("title", "标题"));
        FindIterable<Document> d = ab1.find(where);
        for (Document doc : d) {
            System.out.println(doc.get("_id") + "   " + doc.get("title") + "   " + doc.get("encode"));
        }
    }

    //查询一张表中的数据条数
    @Test
    public void countMongod() {
        MongoCollection<Document> collection = data.getCollection("ab1");
        FindIterable<Document> ab1 = collection.find();
        int i = 0;
        for (Document doc : ab1) {
            i++;
        }
        System.out.println(i);
    }

    //从第一条数据开是查询出前五条数据
    @Test
    public void first5MongodToTitle() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> skip = ab1.find().limit(5).skip(0);
        for (Document doc : skip) {
            System.out.println(doc.get("title"));
        }
    }

    //查询等于18的数据
    @Test
    public void encodeEq18Mongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> encode = ab1.find(Filters.eq("encode", 18));
        for (Document doc : encode) {
            System.out.println(doc.get("title"));
        }
    }

    //查询大于等于18的数据
    @Test
    public void encodeGte18Mongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> encode = ab1.find(Filters.gte("encode", 18));
        for (Document doc : encode) {
            System.out.println(doc.get("title"));
        }
    }

    //查询18到22之间的数据
    @Test
    public void encodeGte18Between22Mongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> encode = ab1.find(Filters.and(Filters.gt("encode", 18), Filters.lt("encode", 22)));
        for (Document doc : encode) {
            System.out.println(doc.get("title"));
        }
    }

    //根据标题查询价格
    @Test
    public void getencodeTotitleMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        FindIterable<Document> documents = ab1.find(Filters.eq("title", "标题1"));
        for (Document document : documents) {
            System.out.println(document.get("encode"));
        }
    }

    //模糊查询
    @Test
    public void LikeMongod() {
        MongoCollection<Document> ab1 = data.getCollection("ab1");
        //固定查询
//        Pattern pattern = Pattern.compile("^标题0$", Pattern.CASE_INSENSITIVE);
        //包含查询
//        Pattern pattern = Pattern.compile("^.*标.*$", Pattern.CASE_INSENSITIVE);
        //左固定
//        Pattern pattern = Pattern.compile("^标题.*$", Pattern.CASE_INSENSITIVE);
        //右固定
        Pattern pattern = Pattern.compile("^.*标题$", Pattern.CASE_INSENSITIVE);

        BasicDBObject obj = new BasicDBObject();
        obj.put("title", pattern);
        FindIterable<Document> documents = ab1.find(obj);
        for (Document document : documents) {
            System.out.println(document.get("encode"));
        }
    }


    //聚合查询
    @Test
    public void groupMongod() {
        MongoCollection<Document> collection = data.getCollection("ab1");
        //对encode的数量进行分组,并且统计出个数
        Document doc = new Document();
        doc.append("_id", "$encode");
        doc.append("count", new Document("$sum", 1));
        //查找encode字段中数量大于18的
        Document matchDoc = new Document();
        matchDoc.put("_id", new Document("$gt", 18.0));
        Document group = new Document("$group", doc);
        Document match = new Document("$match", matchDoc);
        //根据encode字段进行降序排序
        Document sort = new Document("$sort", new Document("_id", 1));
        //将筛选条件添加到文本集合中
        List<Document> doclist = new ArrayList<Document>();
        doclist.add(group);
        doclist.add(match);
        doclist.add(sort);
        //聚合查询并输出
        AggregateIterable<Document> aggregate = collection.aggregate(doclist);
        MongoCursor<Document> iterator = aggregate.iterator();
        while (iterator.hasNext()) {
            Document next = iterator.next();
            double encode = next.getDouble("_id");
            int count = next.getInteger("count", 0);
            System.out.println(encode + "      " + count);
        }
    }

    //在mongod控制台下执行下面三句命令
    /*db.test1.insert([{"title":"java开发手册","author":"孤尽","jobnum":"001"},{"title":"mongod由浅入深","author":"凉风","jobnum":"002"}])
    db.test2.insert([{"jobtitle":"java工程师","jobnum":"001"},{"jobtitle":"数据库工程师","jobnum":"002"}])
    db.test3.insert([{"depart":"开发1部","jobnum":"001"},{"depart":"开发2部","jobnum":"002"}])*/

    //三表带筛选条件关联查询  关键字:lookup
    @Test
    public void lookupMongod() {
        MongoCollection<Document> test1 = data.getCollection("test1");

        List<Bson> aggregateList = new ArrayList<>(1);
        aggregateList.add(Aggregates.lookup("test2", "jobnum", "jobnum", "result"));
        aggregateList.add(Aggregates.match(Filters.ne("result", new ArrayList<String>(0))));

        aggregateList.add(Aggregates.lookup("test3", "jobnum", "jobnum", "results"));
        aggregateList.add(Aggregates.match(Filters.ne("results", new ArrayList<String>(0))));

        aggregateList.add(Aggregates.match(Filters.eq("jobnum", "002")));

        AggregateIterable<Document> aggregateIterable = test1.aggregate(aggregateList);
        //对应得到的json结果参考下方
        for (Document document : aggregateIterable) {
            Object result = document.get("result");
            String[] split = result.toString().split(",");
            System.out.println(split[1].substring(split[1].indexOf("=") + 1));

            Object results = document.get("results");
            String[] splits = results.toString().split(",");
            System.out.println(splits[1].substring(splits[1].indexOf("=") + 1));
        }

    }


//    { "_id" : { "$oid" : "5eba18b5108d9caa7dba842a" },
//        "title" : "java开发手册",
//            "author" : "孤尽",
//            "jobnum" : "001",
//            "result" : [{
//        "_id" : { "$oid" : "5eba1aa2108d9caa7dba8430" },
//        "jobtitle" : "java工程师",
//                "jobnum" : "001"
//    }],
//        "results" : [{
//        "_id" : { "$oid" : "5eba3333108d9caa7dba8432" },
//        "depart" : "开发1部",
//                "jobnum" : "001"
//    }]
//    }

}
 

 

posted @ 2020-05-15 14:47  你是长颈鹿吗  阅读(3338)  评论(0编辑  收藏  举报