mongodb-driver的基本操作操作

首先在项目中添加下面的依赖

 <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.10.1</version>
 </dependency>

完整代码:

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;


/**
 * @author :had
 * @date :Created in 2020/09/28 0028 下午 03:18;20
 */

public class MongodbTest {

    private MongoClient client;
    private MongoDatabase commentdb;
    private MongoCollection<Document> comment;

    @Before
    public void before() {

        //创建连接
        client = new MongoClient("192.168.247.129");
        //打开数据库
        commentdb = client.getDatabase("commentdb");
        //获取集合
        comment = commentdb.getCollection("comment");
    }

    //查询所有
    @Test
    public void test1() {

        //查询
        FindIterable<Document> documents = comment.find();

        for (Document document : documents) {
            System.out.println(document.get("_id"));
            System.out.println(document.get("name"));
        }

    }
    //条件查询
    @Test
    public void test2(){

        //封装查询条件
        BasicDBObject bson=new BasicDBObject("_id","123");
        //查询
        FindIterable<Document> documents=comment.find(bson);
        for (Document document : documents) {
            System.out.println("-----------------------------");
            System.out.println(document.get("_id"));
            System.out.println(document.get("name"));
        }
    }
    //新增
    @Test
    public void test3(){

        //封装
        HashMap<String,Object> map = new HashMap<>();
        map.put("_id","4");
        map.put("name","今天天气好晴朗!!!");

        Document document = new Document(map);
        comment.insertOne(document);
    }

    //修改
    @Test
    public void test4(){

        //修改的条件
        BasicDBObject filter=new BasicDBObject("_id","4");

        //修改的内容

        BasicDBObject update=new BasicDBObject("$set",new Document("userId","8888"));

        comment.updateOne(filter, update);
    }

    //删除
    @Test
    public void test5(){

        //删除的条件
        BasicDBObject filter = new BasicDBObject("_id", "123");

        comment.deleteOne(filter);
    }


    @After
    public void after() {
        //关闭连接
        client.close();
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值