java集成MongoDB

pom配置

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

jdbc连接

ServerAddress serverAddress = new ServerAddress(host, port);
List<ServerAddress> addrs = new ArrayList<>();
addrs.add(serverAddress);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs);

//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);            

选择集合

//选择集合
MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);

文档操作

添加文档

//添加文档
Document document = new Document("title", "oracle").
                    append("description", "database").
                    append("likes", 100).
                    append("by", "Fly");
List<Document> documents = new ArrayList<>();
documents.add(document);
collection.insertMany(documents);

修改文档

collection.updateMany(Filters.eq(fieldName, oldValue), new Document("$set", new Document(fieldName, newValue)));

删除文档

//删除符合条件的第一个文档
collection.deleteOne(Filters.eq(fieldName, value));
//删除所有符合条件的文档
collection.deleteMany (Filters.eq(fieldName, value));

查询文档

//检索查看结果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
    System.out.println(mongoCursor.next());
}

完整测试类

package cn.centychen.example.spring.cloud.biz.a.util;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xzli
 * @Date: 2021/1/21 15:08
 * @Description TODO
 */

@Slf4j
public class MongoDBUtil {

    public static String host = "localhost";

    public static Integer port = 27017;

    public static String databaseName = "db_test1";

    public static String collectionName = "db_test1";

    public static void main(String args[]) {

        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            //ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress(host, port);
            List<ServerAddress> addrs = new ArrayList<>();
            addrs.add(serverAddress);

            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential("username", databaseName, "password".toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            credentials.add(credential);

            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs);

            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
            //选择集合
            MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);

            //添加文档
            Document document = new Document("title", "oracle").
                    append("description", "database").
                    append("likes", 100).
                    append("by", "Fly");
            List<Document> documents = new ArrayList<>();
            documents.add(document);
//            addDocument(collection, documents);
//            updateDocument(collection, "title", document.getString("title"),"oracle");
            deleteDocument(collection,"title", document.getString("title"));
            findDocument(collection);
        } catch (Exception e) {
            log.error(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    public static void addDocument(MongoCollection<Document> collection, List<Document> documents) {
        collection.insertMany(documents);
        log.info("文档插入成功");
    }

    public static void updateDocument(MongoCollection<Document> collection, String fieldName, String oldValue, String newValue) {
        collection.updateMany(Filters.eq(fieldName, oldValue), new Document("$set", new Document(fieldName, newValue)));
        log.info("更新成功");
    }

    public static void deleteDocument(MongoCollection<Document> collection, String fieldName, String value) {
        //删除符合条件的第一个文档
        collection.deleteOne(Filters.eq(fieldName, value));
        //删除所有符合条件的文档
//        collection.deleteMany (Filters.eq(fieldName, value));
    }

    public static void findDocument(MongoCollection<Document> collection) {
        //检索查看结果
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值