首页 > 代码库 > MongoDB简单操作(java版)

MongoDB简单操作(java版)

新建maven项目,添加依赖:

 1 <dependency> 2     <groupId>org.mongodb</groupId> 3     <artifactId>mongo-java-driver</artifactId> 4     <version>3.2.2</version> 5 </dependency> 6 <dependency> 7     <groupId>junit</groupId> 8     <artifactId>junit</artifactId> 9     <version>4.12</version>10 </dependency>

测试代码:

  1 package com.skyer.test;  2   3 import java.util.ArrayList;  4 import java.util.Arrays;  5 import java.util.List;  6   7 import org.bson.Document;  8 import org.junit.After;  9 import org.junit.Before; 10 import org.junit.Test; 11  12 import com.mongodb.BasicDBObject; 13 import com.mongodb.MongoClient; 14 import com.mongodb.MongoClientURI; 15 import com.mongodb.QueryOperators; 16 import com.mongodb.client.ListIndexesIterable; 17 import com.mongodb.client.MongoCollection; 18 import com.mongodb.client.MongoCursor; 19 import com.mongodb.client.MongoDatabase; 20 import com.mongodb.client.result.DeleteResult; 21 import com.mongodb.client.result.UpdateResult; 22  23 public class TestMongo { 24  25     // 声明相关变量 26     MongoClientURI connectionString = null; 27     MongoClient mongoClient = null; 28     MongoDatabase database = null; 29     MongoCollection<Document> collection = null; 30  31     /** 32      * 获取相关对象 33      */ 34     @Before 35     public void getConnection() { 36         connectionString = new MongoClientURI("mongodb://192.168.88.128:27017"); // 服务器连接地址 37         mongoClient = new MongoClient(connectionString); // 获取客户端对象 38         database = mongoClient.getDatabase("skyer"); // 获取数据库 39         collection = database.getCollection("test"); // 获取连接 40     } 41  42     /** 43      * 添加一个 44      */ 45     @Test 46     public void insert() { 47         Document doc = new Document("name", "skyer") 48                             .append("type", "database") 49                             .append("count", 1) 50                             .append("versions", Arrays.asList("v2.7", "v4.2", "v7.2")) 51                             .append("info", new Document("x", 27).append("y", 42)); 52         collection.insertOne(doc); 53     } 54  55     /** 56      * 批量添加 57      */ 58     @Test 59     public void insertMany() { 60         List<Document> docs = new ArrayList<Document>(); 61         for (int i = 0; i < 100; i++) { 62             docs.add(new Document("i", i)); 63         } 64         collection.insertMany(docs); 65     } 66  67     /** 68      * 查询首个 69      */ 70     @Test 71     public void queryFirst() { 72         Document doc = collection.find().first(); 73         System.out.println(doc.toJson()); 74     } 75  76     /** 77      * 查询全部 78      */ 79     @Test 80     public void findAll() { 81         for (Document doc : collection.find()) { 82             System.out.println(doc.toJson()); 83         } 84     } 85  86     /** 87      * 查询全部 88      */ 89     @Test 90     public void findAll2() { 91         MongoCursor<Document> cursor = collection.find().iterator(); 92         while (cursor.hasNext()) { 93             System.out.println(cursor.next().toJson()); 94         } 95     } 96      97     /** 98      * 分页查询 99      */100     @Test101     public void findByPage() {102         MongoCursor<Document> cursor = collection.find().skip(0).limit(5).iterator(); // 查询前五个记录103         while (cursor.hasNext()) {104             System.out.println(cursor.next().toJson());105         }106     }107     108     /**109      * 查询一个110      */111     @Test112     public void findOne() {113         Document doc = collection.find(new Document("i", 27)).first(); // 查询i值为27的记录114         System.out.println(doc.toJson());115     }116 117     /**118      * 条件查询119      */120     @Test121     public void findByCondition1() {122         BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.GT, 95)); // 查询i大于95的记录123         MongoCursor<Document> cursor = collection.find(condition).iterator();124         while (cursor.hasNext()) {125             System.out.println(cursor.next().toJson());126         }127     }128     129     /**130      * 条件查询131      */132     @Test133     public void findByCondition2() { 134         BasicDBObject condition = new BasicDBObject(QueryOperators.AND, 135                                                      new BasicDBObject[] {136                                                          new BasicDBObject().append("i", new BasicDBObject(QueryOperators.GT, 95)), 137                                                          new BasicDBObject().append("i", new BasicDBObject(QueryOperators.LTE, 97))138                                                      }); // 查询95<i<=97的记录139         MongoCursor<Document> cursor = collection.find(condition).iterator();140         while (cursor.hasNext()) {141             System.out.println(cursor.next().toJson());142         }143     }144     145     /**146      * 条件查询:in147      */148     @Test149     public void testIn() {150         BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.IN, new int[] {27, 42}));151         MongoCursor<Document> cursor = collection.find(condition).iterator();152         while (cursor.hasNext()) {153             System.out.println(cursor.next().toJson());154         }155     }156     157     /**158      * 条件查询:not in159      */160     @Test161     public void testNotIn() {162         BasicDBObject condition = new BasicDBObject("i", new BasicDBObject(QueryOperators.NIN, new int[] {34, 47}));163         MongoCursor<Document> cursor = collection.find(condition).iterator();164         while (cursor.hasNext()) {165             System.out.println(cursor.next().toJson());166         }167     }168     169     /**170      * 创建普通索引171      */172     @Test173     public void createIndex() {174         String result = collection.createIndex(new BasicDBObject("name", 1));175         System.out.println(result);176     }177     178     /**179      * 创建文本索引180      */181     @Test182     public void createTextIndex() {183         String result = collection.createIndex(new Document("name", "text"));184         System.out.println(result);185     }186 187     /**188      * 获取所有索引189      */190     @Test191     public void getAllIndex() {192         ListIndexesIterable<Document> list = collection.listIndexes();193         for (Document doc : list) {194             System.out.println(doc.toJson());195         }196     }197     198     /**199      * 删除200      */201     @Test202     public void testDelete() {203         DeleteResult result = collection.deleteOne(new BasicDBObject("i", 2));204         System.out.println(result.getDeletedCount());205     }206 207     /**208      * 批量删除209      */210     @Test211     public void testDeleteMany() {212         DeleteResult result = collection.deleteMany(new BasicDBObject("i", new BasicDBObject(QueryOperators.IN, new int[] {213                 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10214         })));215         System.out.println(result.getDeletedCount());216     }217     218     /**219      * 更新220      */221     @Test222     public void testUpdateOne() {223         UpdateResult result = collection.updateOne(new BasicDBObject("i", 10), new Document("$set", new Document("i", 110)));224         System.out.println(result.getMatchedCount());225     }226 227     /**228      * 释放资源229      */230     @After231     public void releaseConnection() {232         mongoClient.close();233     }234 235 }

 

MongoDB简单操作(java版)