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

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

1.引入Java驱动依赖

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

1
org.mongodbmongodb-driver-sync5.1.0junitjunit4.12testorg.mongodbbson5.1.0org.mongodbmongodb-driver-core5.1.0

2.快速开始

2.1 先在monsh连接建立collection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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中快速开始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
   public void InsertDocument()
   {
       MongoDatabase database = mongoClient.getDatabase("test");
       MongoCollection 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Test
   public void UpdateDocument(){
       MongoDatabase database = mongoClient.getDatabase("test");
       MongoCollection 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
   public void testFindDocuments(){
       MongoDatabase database = mongoClient.getDatabase("test");
       MongoCollection collection = database.getCollection("map");
       // 创建检索条件
       /*Bson projectionFields = Projections.fields(
               Projections.include("name", "shanghai"),
               Projections.excludeId());*/
       // 匹配过滤检索文档
       MongoCursor 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
   public void DeleteDocument(){
       MongoDatabase database = mongoClient.getDatabase("test");
       MongoCollection 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操作内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/11836.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部