当前位置: 代码网 > it编程>编程语言>Java > Java中连接Mongodb进行增删改查的操作详解

Java中连接Mongodb进行增删改查的操作详解

2024年06月17日 Java 我要评论
1.引入java驱动依赖注意:启动服务的时候需要加ip绑定需要引入依赖<dependency> <groupid>org.mongodb</groupid>

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);
        }
    }

到此这篇关于java中连接mongodb进行增删改查的操作详解的文章就介绍到这了,更多相关java连接mongodb操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com