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 }
时间: 2024-08-01 04:54:41

MongoDB简单操作(java版)的相关文章

mongodb简单操作

1.执行mongod.exe 服务器启动  后面可跟参数说明启动的数据库和日志. eg: mongod.exe --bind_ip 127.0.0.1 --logpath "F:\data\dbConf\mongodb.log" --logappend --dbpath "F:\data\db" --port 19901 --serviceName "mongodb1" --serviceDisplayName "mongodbAll&

java版的QQ小程序

转载自:http://blog.csdn.net/lihongxun945/article/details/6114290 这是一个简单的java版的QQ小程序. 包括一个简单的服务器和一个简单的客户端. 运行时,先运行服务器,然后在运行客户端,就可以进行聊天了. 默认的配置是localhost,端口4545,更改ip就可以在两天电脑上进行聊天了. 目前不支持内网和外网之间的访问,也不支持多人聊天. 因为这只是一个简单的例子,感兴趣的同学可以通过改进,实现多人聊天和内外网之间的访问. 效果图:

java 对mongodb的操作

java 对mongodb的操作 1.1连单台mongodb Mongo mg = newMongo();//默认连本机127.0.0.1  端口为27017 Mongo mg = newMongo(ip);//可以指定ip 端口默认为27017 Mongo mg = newMongo(ip,port);//也可以指定ip及端口号 1.2连双台mongodb //ip为主机ip地址,port为端口号,dataBaseName相当于数据库名 DBAddress left = new DBAddre

SWFUpload简单使用样例 Java版(JSP)

SWFUpload官方的样例都是PHP的,在这里提供一个Java版的最简单的使用样例,使用JSP页面完毕全部操作. 实现上传,分为三步: 1.JavaScript设置SWFUpload部分(与官方样例类似): Js代码   var upload; window.onload = function() { upload = new SWFUpload({ // 处理文件上传的url upload_url: "${pageContext.request.contextPath}/swfupload/

ORACLE的安装与网页版创建表空间的简单操作以及PLsql的简单操作

1.oracle的安装: 安装简单易学,在这里不做解释.下载看装包后耐心等待,注意安装目录不要有中文字符,尽量按照指定目录进行安装.安装完成后会占用有大约5g的内存. 如果要卸载oracle,需要用其自带的卸载工具进行卸载[universal installer],然后删除注册表项,删除环境变量,删除目录并且重新启动计算机. 2.在网页版进行创建表空间: 进入网页版: 在电脑的服务中我们可以看到一共有7个oracle的服务项目,其中只有三个是正在启动中.这三项中,只有当OracleDBConso

Java时间简单操作

使用java操作时间感觉真真蛋疼,还是我大C#舒服,一个DateTime全部搞定 这里的Date指的是java.util.Date 获取当前时间: // 创建一个当前时间的Date对象 Date time = new Date(); 蛋疼的地方,对时间增.减操作: // 使用Calendar类对时间增.减操作 Calendar c = Calendar.getInstance();// 获得一个Calendar实例,该类是抽象类所以不可以使用new构造方法 // 使用setTime方法创建一个时

C# 对MongoDB 进行增删改查的简单操作

C# 对MongoDB 进行增删改查的简单操作 下面演示下C#操作MongoDB驱动的简单的增删改查代码 运用到的MongoDB支持的C#驱动,当前版本为1.6.0 下载地址:https://github.com/mongodb/mongo-csharp-driver/downloads 1,连接数据库 /// <summary> /// 数据库连接 /// </summary> private const string conn = "mongodb://127.0.0

Python mongoDB 的简单操作

#!/usr/bin/env python # coding:utf-8 # Filename:mongodb.py from pymongo import MongoClient,ASCENDING,DESCENDING import datetime # connection with mongoclient client=MongoClient() # getting a database db=client.test # getting a collection collection=d

关于时间的操作(Java版)——获取给定时间与当前系统时间的差值(以毫秒为单位)

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Test { /** * 获取给定时间与当前系统时间的差值(以毫秒为单位) * * @author GaoHuanjie */ public long getTimeDifferenceBetweenSystemTimeAndParamTime(String paramTime) { DateFor