zoukankan      html  css  js  c++  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     @Test
    101     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     @Test
    112     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     @Test
    121     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     @Test
    133     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      * 条件查询:in
    147      */
    148     @Test
    149     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 in
    159      */
    160     @Test
    161     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     @Test
    173     public void createIndex() {
    174         String result = collection.createIndex(new BasicDBObject("name", 1));
    175         System.out.println(result);
    176     }
    177     
    178     /**
    179      * 创建文本索引
    180      */
    181     @Test
    182     public void createTextIndex() {
    183         String result = collection.createIndex(new Document("name", "text"));
    184         System.out.println(result);
    185     }
    186 
    187     /**
    188      * 获取所有索引
    189      */
    190     @Test
    191     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     @Test
    202     public void testDelete() {
    203         DeleteResult result = collection.deleteOne(new BasicDBObject("i", 2));
    204         System.out.println(result.getDeletedCount());
    205     }
    206 
    207     /**
    208      * 批量删除
    209      */
    210     @Test
    211     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, 10
    214         })));
    215         System.out.println(result.getDeletedCount());
    216     }
    217     
    218     /**
    219      * 更新
    220      */
    221     @Test
    222     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     @After
    231     public void releaseConnection() {
    232         mongoClient.close();
    233     }
    234 
    235 }
    作者:Oven
    个人网站:http://www.cloveaire.com
    个性签名:大亨以正,莫退初心!
    如果觉得这篇文章对你有帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
  • 相关阅读:
    BestCoder Round #84
    codeforces#689BMike and Shortcuts
    POJ2985 并查集+线段树 求第k大的数
    Trie树模板 POJ1056
    新建zabbix数据库
    python输出菱形
    wmi获取计算机信息
    python测试IP地址是否ping通
    手机安装python环境
    Centos 8 安装zabbix 爬坑
  • 原文地址:https://www.cnblogs.com/Oven5217/p/6898414.html
Copyright © 2011-2022 走看看