【Mongo】Java操作MongoDB

2023-12-28 10:58:48

Java操作MongoDB

MongoDB支持C、C++、C#、GO、Java、NodeJS、PHP、Python、Ruby、Rust、Scala和Swift语言的驱动程序,MongoDB 提供了当前所有主流开发语言的数据库驱动包,开发人员使用以上任何一种主流开发语言都可以轻松编程,实现访问MongoDB 数据库。[^3]

现在只介绍Java语言通过MongoDB驱动程序对MongoDB数据库的基本操作,mongodb-dirver-sync是MongoDB官方推出的驱动程序,这里使用的版本为4.6.1,MongoDB版本为v5.0.2,jdk版本为jdk1.8具体的数据库和驱动版本的兼容性关系参照MongoDB Compatibility

准备工作

  1. 引入maven依赖

    在项目中引入如下依赖,具体版本根据需要连接的MongoDB数据库自行确定,这里是4.6.1

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongodb-driver-sync</artifactId>
    <version>4.6.1</version>
</dependency>
  1. 编辑配置文件

    配置文件的作用是用来保存MongoDB的连接信息,如ip,端口号等,在实际开发过程中对这种配置信息尽量使用配置文件,减少硬编码。配置文件内容如下:

   # 配置文件保存路径为:resource/config/mongodb.properties
   mongodb.uri.host=127.0.0.1
   mongodb.uri.port=27017
   mongodb.uri.database=MongoStudy
   mongodb.database.defaultCollection=game
  1. 建立连接后进行相关操作

    通过代码读取配置信息,建立MongoDB连接并进行相关操作,具体代码如下:

   package top.sunyog.mongo;
   
   import com.mongodb.client.*;
   import com.mongodb.client.model.Filters;
   import org.bson.Document;
   import org.bson.conversions.Bson;
   
   import java.io.*;
   import java.net.URL;
   import java.text.MessageFormat;
   import java.util.Properties;
   
   public class MongoDemoApp {
       public static void main(String[] args) {
           //读取properties配置文件
           Properties properties = new Properties();
           URL uri = MongoDemoApp.class.getClassLoader().getResource("config/mongodb.properties");
           try (InputStream in = new FileInputStream(uri.getFile());
                BufferedInputStream bin = new BufferedInputStream(in)) {
               properties.load(bin);
               String host = properties.getProperty("mongodb.uri.host");
               String port = properties.getProperty("mongodb.uri.port");
               String db = properties.getProperty("mongodb.uri.database");
               String defaultColl = properties.getProperty("mongodb.database.defaultCollection");
               
               //构建数据库url
               final String urlFormatter="mongodb://{0}:{1}";
               String conn = MessageFormat.format(urlFormatter, host, port);
               //建立连接
               MongoClient client = MongoClients.create(conn);
               //进行数据库相关操作
               //...
           } catch (FileNotFoundException e) {
               throw new RuntimeException(e);
           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }
   }

插入数据

和MongoDB shell一样,使用Java向MongoDB插入数据也有两种方法,insertOne()insertMany(),两个函数的区别在于入参,一个是Document对象,一个是List<Document>对象。主要用法如下:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.InsertOneResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.Arrays;

public class InsertDemo {
    private void insertDocument(MongoCollection coll) {
        Document doc = new Document();
        doc.append("name", "terraria").append("price", 18);
        doc.put("platform", Arrays.asList("PSX","XBOX","steam","switch"));
        InsertOneResult insertRes = coll.insertOne(doc);
    }
}

通过以下查询插入的数据:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.InsertOneResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.Arrays;

public class InsertDemo {
    private void findById(MongoCollection coll,InsertOneResult insertRes){
        Bson filter = Filters.eq("_id", insertRes.getInsertedId());
        MongoCursor cursor = coll.find(filter).iterator();
        while (cursor.hasNext()){
            System.out.println(cursor.next());
        }
    }
}

控制台打印结果如下:

Document{{_id=62c53f733ae2f874816f4a85, name=terraria, price=18, platform=[PSX, XBOX, steam, switch]}}

批量插入数据代码样例:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class InsertDemo { 
	private void insertDocuments(MongoCollection coll) {
    	//生成数据
        List<Document> documents = Arrays.asList(
                new Document().append("name", "overcooked! 2").append("price", 24),
                new Document().append("name","titan fall 2").append("price",25)
        );
    	//插入数据
        InsertManyResult insertManyResult = coll.insertMany(documents);
    	//查询数据
        for (Map.Entry<Integer, BsonValue> entry : insertManyResult.getInsertedIds().entrySet()) {
            BsonValue idVal = entry.getValue();
            coll.find(Filters.eq("_id",idVal)).forEach(o->{
                System.out.println(o);
            });
        }
    }
}

执行程序,打印出的数据结果如下:

Document{{_id=62c6395b615f8a447cb82710, name=overcooked! 2, price=24}}
Document{{_id=62c6395b615f8a447cb82711, name=titan fall 2, price=25}}

带选项的批量插入:

List<Document> documents = Arrays.asList(
        new Document().append("name", "overcooked! 2").append("price", 24),
        new Document().append("name", "pummel party").append("price", 30),
        new Document().append("name", "cup head").append("price", 47),
        new Document().append("name", "ori").append("price", 29)
	);
InsertManyOptions options = new InsertManyOptions().ordered(false);
InsertManyResult res = coll.insertMany(documents, options);

删除数据

deleteOne()方法代码样例:

package top.sunyog.mongo.delete;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

public class DeleteDemo {
    private void deleteDocument(MongoCollection coll) {
        DeleteResult res = coll.deleteOne(Filters.eq("name", "titan fall 2"));
        System.out.println(res);
    }
}

执行结果:

AcknowledgedDeleteResult{deletedCount=1}

deleteMany()方法代码样例:

package top.sunyog.mongo.delete;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

public class DeleteDemo {   
	private void deleteManyDocuments(MongoCollection coll) {
        Bson filter_1 = Filters.eq("name", "overcooked! 2");
        Bson filter_2 = Filters.eq("name", "terraria");
        Bson filter = Filters.or(filter_1, filter_2);
        DeleteResult res = coll.deleteMany(filter);
        long count = res.getDeletedCount();
        System.out.println("delete many function result: count="+count);
    }
}

执行结果:

delete many function result: count=2

更新数据

替换文档

replaceOne()方法用于对文档进行替换, 实例代码如下:

package top.sunyog.mongo.update;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;

import java.util.Arrays;

public class UpdateDemo {
    private void replaceOneDoc(MongoCollection<Document> coll) {
        Document doc = new Document().append("name", "ori").append("price", 129)
                .append("platform", Arrays.asList("switch", "steam"));
        UpdateResult res = coll.replaceOne(Filters.eq("name", "ori"), doc);
        System.out.println(res);
    }
}

测试更新结果:

> db.game.find({"name":"ori"}).pretty()
{
        "_id" : ObjectId("62c64528eb52555d87933438"),
        "name" : "ori",
        "price" : 129,
        "platform" : [
                "switch",
                "steam"
        ]
}

文章来源:https://blog.csdn.net/qq_43408971/article/details/135194326
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。