Java中连接Mongodb进行操作

1.引入Java驱动依赖

注意:启动服务的时候需要加ip绑定
需要引入依赖

<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>5.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/bson -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>bson</artifactId>
      <version>5.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-core -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-core</artifactId>
      <version>5.1.0</version>
    </dependency>

2.快速开始

2.1 先在monsh连接建立collection

db.players.insertOne({name:"palyer1",height:181,weigh:90})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e0a522ef6dba6a26a13')
}
test> db.players.insertOne({name:"palyer2",height:190,weigh:100})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e18522ef6dba6a26a14')
}
test> db.players.find()
[
  {
    _id: ObjectId('665c5e0a522ef6dba6a26a13'),
    name: 'player1',
    height: 181,
    weigh: 90
  },
  {
    _id: ObjectId('665c5e18522ef6dba6a26a14'),
    name: 'player2',
    height: 190,
    weigh: 100
  }
]

2.2 java中快速开始

public class QuickStart {

    public static void main(String[] args) {
        // 连接的url
        String uri = "mongodb://node02:27017";
        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("test");
            MongoCollection<Document> collection = database.getCollection("players");
            Document doc = collection.find(eq("name", "palyer2")).first();
            if (doc != null) {
                //{"_id": {"$oid": "665c5e18522ef6dba6a26a14"}, "name": "palyer2", "height": 190, "weigh": 100}
                System.out.println(doc.toJson());
            } else {
                System.out.println("No matching documents found.");
            }
        }
    }

}

2.3 Insert a Document

 @Test
    public void InsertDocument()
    {
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        try {
            // 插入地图文档
            InsertOneResult result = collection.insertOne(new Document()
                    .append("_id", new ObjectId())
                    .append("name", "beijing")
                    .append("longitude", "40°N")
                    .append("latitude", "116°E"));
            //打印文档的id
            //Success! Inserted document id: BsonObjectId{value=665c6424a080bb466d32e645}
            System.out.println("Success! Inserted document id: " + result.getInsertedId());
            // Prints a message if any exceptions occur during the operation
        } catch (MongoException me) {
            System.err.println("Unable to insert due to an error: " + me);
        }

2.4 Update a Document

 @Test
    public void UpdateDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        //构造更新条件
        Document query = new Document().append("name",  "beijing");
        // 指定更新的字段
        Bson updates = Updates.combine(
                Updates.set("longitude", "40.0N"),
                Updates.set("latitude", "116.0E")
        );
        // Instructs the driver to insert a new document if none match the query
        UpdateOptions options = new UpdateOptions().upsert(true);
        try {
            // 更新文档
            UpdateResult result = collection.updateOne(query, updates, options);
            // Prints the number of updated documents and the upserted document ID, if an upsert was performed
            System.out.println("Modified document count: " + result.getModifiedCount());
            System.out.println("Upserted id: " + result.getUpsertedId());

        } catch (MongoException me) {
            System.err.println("Unable to update due to an error: " + me);
        }
    }

2.5 Find a Document

 @Test
    public void testFindDocuments(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        // 创建检索条件
        /*Bson projectionFields = Projections.fields(
                Projections.include("name", "shanghai"),
                Projections.excludeId());*/
        // 匹配过滤检索文档
        MongoCursor<Document> cursor = collection.find(eq("name", "shanghai"))
                //.projection(projectionFields)
                .sort(Sorts.descending("longitude")).iterator();
        // 打印检索到的文档
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }

检索

2.6 Delete a Document

 @Test
    public void DeleteDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        Bson query = eq("name", "shanghai");
        try {
            // 删除名字为shanghai的地图
            DeleteResult result = collection.deleteOne(query);
            System.out.println("Deleted document count: " + result.getDeletedCount());
            // 打印异常消息
        } catch (MongoException me) {
            System.err.println("Unable to delete due to an error: " + me);
        }
    }
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在 Java 使用 MongoDB,你需要先将 MongoDB Java 驱动程序添加到你的项目。可以通过 Maven 或 Gradle 等构建工具来添加依赖项。 添加依赖项后,你需要创建一个 MongoClient 对象,该对象表示与 MongoDB 数据库的连接。可以通过以下代码创建一个 MongoClient 对象: ``` MongoClient mongoClient = new MongoClient("localhost", 27017); ``` 这将创建一个连接到本地主机上端口号为 27017 的 MongoDB 实例的 MongoClient 对象。 添加文档: 要向 MongoDB 添加文档,可以使用以下代码: ``` MongoCollection<Document> collection = mongoClient.getDatabase("mydb").getCollection("users"); Document document = new Document("name", "John Doe") .append("age", 30) .append("email", "johndoe@example.com"); collection.insertOne(document); ``` 这将向名为“mydb”的数据库名为“users”的集合添加一个名为“John Doe”的文档。 查询文档: 要查询 MongoDB 的文档,可以使用以下代码: ``` MongoCollection<Document> collection = mongoClient.getDatabase("mydb").getCollection("users"); Document query = new Document("name", "John Doe"); FindIterable<Document> cursor = collection.find(query); for (Document document : cursor) { System.out.println(document.toJson()); } ``` 这将查询名为“John Doe”的文档,并将结果打印到控制台上。 以上是 Java 连接操作 MongoDB 的基本操作,更多详细的操作可以查看 MongoDB Java 驱动程序的官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小刘同学要加油呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值