MongoDB基本用法
分享一下我经常用到的自己写的mongo用法示例
该示例基于当前最新的mongo驱动,版本为mongo-2.10.1.jar,用junit写的单元测试。
TestCase.java
- package com.wujintao.mongo;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
- import java.util.regex.Pattern;
- import org.junit.Test;
- import com.mongodb.AggregationOutput;
- import com.mongodb.BasicDBList;
- import com.mongodb.BasicDBObject;
- import com.mongodb.BasicDBObjectBuilder;
- import com.mongodb.DB;
- import com.mongodb.DBCollection;
- import com.mongodb.DBCursor;
- import com.mongodb.DBObject;
- import com.mongodb.MapReduceCommand;
- import com.mongodb.MapReduceOutput;
- import com.mongodb.Mongo;
- import com.mongodb.QueryBuilder;
- import com.mongodb.WriteConcern;
- public class TestCase {
- //DBCursor cursor = coll.find(condition).addOption(Bytes.QUERYOPTION_NOTIMEOUT);//设置游标不要超时
- @Test
- /**
- * 获取所有数据库实例
- */
- public void testGetDBS() {
- List<String> dbnames = MongoUtil.getMong().getDatabaseNames();
- for (String dbname : dbnames) {
- System.out.println("dbname:" + dbname);
- }
- }
- @Test
- /**
- * 删除数据库
- */
- public void dropDatabase() {
- MongoUtil.getMong().dropDatabase("my_new_db");
- }
- @Test
- /**
- * 查询所有表名
- */
- public void getAllCollections() {
- Set<String> colls = MongoUtil.getDB().getCollectionNames();
- for (String s : colls) {
- System.out.println(s);
- }
- }
- @Test
- public void dropCollection() {
- MongoUtil.getColl("jellonwu").drop();
- }
- /**
- * 添加一条记录
- */
- @Test
- public void addData() {
- DBCollection coll = MongoUtil.getColl("wujintao");
- BasicDBObject doc = new BasicDBObject();
- doc.put("name", "MongoDB");
- doc.put("type", "database");
- doc.put("count", 1);
- BasicDBObject info = new BasicDBObject();
- info.put("x", 203);
- info.put("y", 102);
- doc.put("info", info);
- coll.insert(doc);
- // 设定write concern,以便操作失败时得到提示
- coll.setWriteConcern(WriteConcern.SAFE);
- }
- @Test
- /**
- * 创建索引
- */
- public void createIndex() {
- MongoUtil.getColl("wujintao").createIndex(new BasicDBObject("i", 1));
- }
- @Test
- /**
- * 获取索引信息
- */
- public void getIndexInfo() {
- List<DBObject> list = MongoUtil.getColl("hems_online").getIndexInfo();
- for (DBObject o : list) {
- System.out.println(o);
- }
- }
- @Test
- /**
- * 添加多条记录
- */
- public void addMultiData() {
- for (int i = 0; i < 100; i++) {
- MongoUtil.getColl("wujintao").insert(
- new BasicDBObject().append("i", i));
- }
- List<DBObject> docs = new ArrayList<DBObject>();
- for (int i = 0; i < 50; i++) {
- docs.add(new BasicDBObject().append("i", i));
- }
- MongoUtil.getColl("wujintao").insert(docs);
- // 设定write concern,以便操作失败时得到提示
- MongoUtil.getColl("wujintao").setWriteConcern(WriteConcern.SAFE);
- }
- @Test
- /**
- * 查找第一条记录
- */
- public void findOne() {
- DBObject myDoc = MongoUtil.getColl("wujintao").findOne();
- System.out.println(myDoc);
- }
- @Test
- /**
- * 获取表中所有记录条数
- */
- public void count() {
- System.out.println(MongoUtil.getColl("wujintao").getCount());
- System.out.println(MongoUtil.getColl("wujintao").count());
- }
- @Test
- /**
- * 获取查询结果集的记录数
- */
- public void getCount() {
- DBObject query = new BasicDBObject("name", "a");
- long count = MongoUtil.getColl("wujintao").count(query);
- System.out.println(count);
- }
- @Test
- /**
- * 查询所有结果
- */
- public void getAllDocuments() {
- DBCursor cursor = MongoUtil.getColl("wujintao").find();
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- /**
- * 按照一个条件查询
- */
- public void queryByConditionOne() {
- BasicDBObject query = new BasicDBObject();
- query.put("name", "MongoDB");
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- /**
- * AND多条件查询,区间查询
- */
- public void queryMulti() {
- BasicDBObject query = new BasicDBObject();
- // 查询j不等于3,k大于10的结果集
- query.put("j", new BasicDBObject("$ne", 3));
- query.put("k", new BasicDBObject("$gt", 10));
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- /**
- * 区间查询
- * select * from table where i >50
- */
- public void queryMulti2() {
- BasicDBObject query = new BasicDBObject();
- query = new BasicDBObject();
- query.put("i", new BasicDBObject("$gt", 50)); // e.g. find all where i >
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- /**
- * 区间查询
- * select * from table where 20 < i <= 30
- //比较符
- //"$gt": 大于
- //"$gte":大于等于
- //"$lt": 小于
- //"$lte":小于等于
- //"$in": 包含
- */
- public void queryMulti3() {
- BasicDBObject query = new BasicDBObject();
- query = new BasicDBObject();
- query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- /**
- * 组合in和and select * from test_Table where (a=5 or b=6) and (c=5 or d = 6)
- */
- public void queryMulti4() {
- BasicDBObject query11 = new BasicDBObject();
- query11.put("a", 1);
- BasicDBObject query12 = new BasicDBObject();
- query12.put("b", 2);
- List<BasicDBObject> orQueryList1 = new ArrayList<BasicDBObject>();
- orQueryList1.add(query11);
- orQueryList1.add(query12);
- BasicDBObject orQuery1 = new BasicDBObject("$or", orQueryList1);
- BasicDBObject query21 = new BasicDBObject();
- query21.put("c", 5);
- BasicDBObject query22 = new BasicDBObject();
- query22.put("d", 6);
- List<BasicDBObject> orQueryList2 = new ArrayList<BasicDBObject>();
- orQueryList2.add(query21);
- orQueryList2.add(query22);
- BasicDBObject orQuery2 = new BasicDBObject("$or", orQueryList2);
- List<BasicDBObject> orQueryCombinationList = new ArrayList<BasicDBObject>();
- orQueryCombinationList.add(orQuery1);
- orQueryCombinationList.add(orQuery2);
- BasicDBObject finalQuery = new BasicDBObject("$and",
- orQueryCombinationList);
- DBCursor cursor = MongoUtil.getColl("wujintao").find(finalQuery);
- }
- @Test
- /**
- * IN查询
- * if i need to query name in (a,b); just use { name : { $in : ['a', 'b'] } }
- * select * from things where name='a' or name='b'
- * @param coll
- */
- public void queryIn() {
- BasicDBList values = new BasicDBList();
- values.add("a");
- values.add("b");
- BasicDBObject in = new BasicDBObject("$in", values);
- DBCursor cursor = MongoUtil.getColl("wujintao").find(
- new BasicDBObject("name", in));
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- /**
- * 或查询
- * select * from table where name = '12' or title = 'p'
- * @param coll
- */
- public void queryOr() {
- QueryBuilder query = new QueryBuilder();
- query.or(new BasicDBObject("name", 12), new BasicDBObject("title", "p"));
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query.get()).addSpecial("$returnKey", "");
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- @Test
- public void customQueryField() throws UnknownHostException{
- Mongo mongo = new Mongo("localhost", 27017);
- DB db = mongo.getDB("zhongsou_ad");
- BasicDBObjectBuilder bulder = new BasicDBObjectBuilder();
- bulder.add("times",1);
- bulder.add("aid",1);
- DBCursor cusor = db.getCollection("ad_union_ad_c_1").find(new BasicDBObject(),bulder.get());
- for (DBObject dbObject : cusor) {
- System.out.println(dbObject);
- }
- }
- @Test
- public void mapReduce() throws UnknownHostException{
- Mongo mongo = new Mongo("localhost", 27017);
- DB db = mongo.getDB("zhongsou_ad");
- /***
- * book1 = {name : "Understanding JAVA", pages : 100}
- * book2 = {name : "Understanding JSON", pages : 200}
- * db.books.save(book1)
- * db.books.save(book2)
- * book = {name : "Understanding XML", pages : 300}
- * db.books.save(book)
- * book = {name : "Understanding Web Services", pages : 400}
- * db.books.save(book)
- * book = {name : "Understanding Axis2", pages : 150}
- * db.books.save(book)
- *
- var map = function() {
- var category;
- if ( this.pages >= 250 )
- category = 'Big Books';
- else
- category = "Small Books";
- emit(category, {name: this.name});
- };
- var reduce = function(key, values) {
- var sum = 0;
- values.forEach(function(doc) {
- sum += 1;
- });
- return {books: sum};
- };
- var count = db.books.mapReduce(map, reduce, {out: "book_results"});
- */
- try {
- DBCollection books = db.getCollection("books");
- BasicDBObject book = new BasicDBObject();
- book.put("name", "Understanding JAVA");
- book.put("pages", 100);
- books.insert(book);
- book = new BasicDBObject();
- book.put("name", "Understanding JSON");
- book.put("pages", 200);
- books.insert(book);
- book = new BasicDBObject();
- book.put("name", "Understanding XML");
- book.put("pages", 300);
- books.insert(book);
- book = new BasicDBObject();
- book.put("name", "Understanding Web Services");
- book.put("pages", 400);
- books.insert(book);
- book = new BasicDBObject();
- book.put("name", "Understanding Axis2");
- book.put("pages", 150);
- books.insert(book);
- String map = "function() { "+
- "var category; " +
- "if ( this.pages >= 250 ) "+
- "category = 'Big Books'; " +
- "else " +
- "category = 'Small Books'; "+
- "emit(category, {name: this.name});}";
- String reduce = "function(key, values) { " +
- "var sum = 0; " +
- "values.forEach(function(doc) { " +
- "sum += 1; "+
- "}); " +
- "return {books: sum};} ";
- MapReduceCommand cmd = new MapReduceCommand(books, map, reduce,
- null, MapReduceCommand.OutputType.INLINE, null);
- MapReduceOutput out = books.mapReduce(cmd);
- for (DBObject o : out.results()) {
- System.out.println(o.toString());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Test
- public void GroupByManyField() throws UnknownHostException{
- //此方法没有运行成功
- Mongo mongo = new Mongo("localhost", 27017);
- DB db = mongo.getDB("libary");
- DBCollection books = db.getCollection("books");
- BasicDBObject groupKeys = new BasicDBObject();
- groupKeys.put("total", new BasicDBObject("$sum","pages"));
- BasicDBObject condition = new BasicDBObject();
- condition.append("pages", new BasicDBObject().put("$gt", 0));
- String reduce = "function(key, values) { " +
- "var sum = 0; " +
- "values.forEach(function(doc) { " +
- "sum += 1; "+
- "}); " +
- "return {books: sum};} ";
- /**
- BasicDBList basicDBList = (BasicDBList)db.getCollection("mongodb中集合编码或者编码")
- .group(DBObject key, --分组字段,即group by的字段
- DBObject cond, --查询中where条件
- DBObject initial, --初始化各字段的值
- String reduce, --每个分组都需要执行的Function
- String finial --终结Funciton对结果进行最终的处理
- */
- DBObject obj = books.group(groupKeys, condition, new BasicDBObject(), reduce);
- System.out.println(obj);
- AggregationOutput ouput = books.aggregate(new BasicDBObject("$group",groupKeys));
- System.out.println(ouput.getCommandResult());
- System.out.println(books.find(new BasicDBObject("$group",groupKeys)));
- }
- @Test
- /**
- * 分页查询
- */
- public void pageQuery() {
- DBCursor cursor = MongoUtil.getColl("wujintao").find().skip(0)
- .limit(10);
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- }
- /**
- * 模糊查询
- */
- public void likeQuery() {
- Pattern john = Pattern.compile("joh?n");
- BasicDBObject query = new BasicDBObject("name", john);
- // finds all people with "name" matching /joh?n/i
- DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
- }
- @Test
- /**
- * 条件删除
- */
- public void delete() {
- BasicDBObject query = new BasicDBObject();
- query.put("name", "xxx");
- // 找到并且删除,并返回删除的对象
- DBObject removeObj = MongoUtil.getColl("wujintao").findAndRemove(query);
- System.out.println(removeObj);
- }
- @Test
- /**
- * 更新
- */
- public void update() {
- BasicDBObject query = new BasicDBObject();
- query.put("name", "liu");
- DBObject stuFound = MongoUtil.getColl("wujintao").findOne(query);
- stuFound.put("name", stuFound.get("name") + "update_1");
- MongoUtil.getColl("wujintao").update(query, stuFound);
- }
- }
这里面涉及到的MongoUtil.java如下:
- package com.wujintao.mongo;
- import java.net.UnknownHostException;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import com.mongodb.DB;
- import com.mongodb.DBCollection;
- import com.mongodb.Mongo;
- /**
- * to see:http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency
- * Mongo工具类:设计为单例模式,每当月份发生变化,数据库连接名称就会发生变化,这是业务规则
- * 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为10个)。
- * 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,我们可以用以下方式保证一致性:
- * DB mdb = mongo.getDB('dbname');
- * mdb.requestStart();
- * // 业务代码
- * mdb.requestDone();
- * DB和DBCollection是绝对线程安全的
- * @author wujintao
- */
- public class MongoUtil{
- private static Mongo mongo;
- private static DBCollection coll;
- private static Log log = LogFactory.getLog(MongoUtil.class);
- private static DB db;
- static{
- try {
- MongoOptions options = new MongoOptions();
- options.autoConnectRetry = true;
- options.connectionsPerHost = 1000;
- options.maxWaitTime = 5000;
- options.socketTimeout = 0;
- options.connectTimeout = 15000;
- options.threadsAllowedToBlockForConnectionMultiplier = 5000;
- //事实上,Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了
- mongo = new Mongo(new ServerAddress(DBMongoConfig.getHost(),DBMongoConfig.getPort()),options);
- //mongo = new Mongo(DBMongoConfig.getHost(),DBMongoConfig.getPort());
- // or, to connect to a replica set, supply a seed list of members
- // Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost",
- // 27017),
- // new ServerAddress("localhost", 27018),
- // new ServerAddress("localhost", 27019)));
- // 注意Mongo已经实现了连接池,并且是线程安全的。
- // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
- // boolean auth = db.authenticate(myUserName, myPassword);
- } catch (UnknownHostException e) {
- log.info("get mongo instance failed");
- }
- }
- public static DB getDB(){
- if(db==null){
- db = mongo.getDB(DBMongoConfig.getDbname());
- }
- return db;
- }
- public static Mongo getMong(){
- return mongo;
- }
- public static DBCollection getColl(String collname){
- return getDB().getCollection(collname);
- }
- }
MongoDB基本用法的更多相关文章
- Mongodb基础用法及查询操作[转载]
插入多条测试数据> for(i=1;i<=1000;i++){... db.blog.insert({"title":i,"content":&qu ...
- mongodb的用法
关于新版(2.***)的c#用法,网上基本没有.昨天折腾半天,去构造server,发现现在新版本不需要了,文档是这样的,大概意思,无需像原来那样获取server,直接从client获取db就行了. h ...
- Mongodb基础用法及查询操作
插入多条测试数据> for(i=1;i<=1000;i++){... db.blog.insert({"title":i,"content":&qu ...
- MongoDB查询用法大全
转载 http://blog.163.com/lgh_2002/blog/static/440175262012052116455/ 详见官方的手册: http://www.mongodb.org/d ...
- 爬虫入门【8】Python连接MongoDB的用法简介
MongoDB的连接和数据存取 MongoDB是一种跨平台,面向文档的NoSQL数据库,提供高性能,高可用性并且易于扩展. 包含数据库,集合,文档等几个重要概念. 我们在这里不介绍MongoDB的特点 ...
- mongodb简单用法
修改器: $inc: 增加已有的键值,如果键值不存在就创建一个 数据库中存在这样的数据:{ , "url": "www.example.com", }db.fz ...
- MongoDB高级用法
MongoDB高级查询用法大全 转载 http://blog.163.com/lgh_2002/blog/static/440175262012052116455/ 详见官方的手册:http://ww ...
- mongodb(基础用法)
驱动和客户端库 https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/drivers.html#id2 https://m ...
- mongodb基础用法
安装部分 mongodb配置方法 mongodb的安装目录 C:\MongoDB\Server\3.2\bin 创建以下目录 c:\mongo\log c:\mongo\db 创建mongodb的配置 ...
随机推荐
- 王立平--svnserver搭建
1.下载 2.安装打开. 3.新建存储库. ---------------------------------- 4.新建用户. watermark/2/text/aHR0cDovL2Jsb2cuY3 ...
- MySQL-LAST_INSERT_ID();使用注意事项
第一.查询和插入所使用的Connection对象必须是同一个才可以,否则返回值是不可预料的. mysql> SELECT LAST_INSERT_ID(); -> 100 使 用这函数向一 ...
- Docker入门二
容器管理 1.docker create创建一个容器,但容器并没启动,就和我们创建虚拟机一样,创建了虚拟机后没启动 [root@centos-02 ~]# docker create -it cent ...
- /usr/lib64改名字风波
注:本文描述请勿模仿,仅限万一遇到这种情况一试. 一不小心做了一个操作: cd /usr mv lib64 lib64-bak 然后奇异的发现: cp不能用了!ls也不能用了…… 提示信息如下: -b ...
- string.Format字符串格式化说明
1.格式化货币(跟系统的环境有关,中文系统默认格式化人民币,英文系统格式化美元) string.Format("{0:C}",0.2) 结果为:¥0.20 (英文操作系统结果:$0 ...
- Python 爬虫实例(1)—— 爬取百度图片
爬取百度图片 在Python 2.7上运行 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: loveNight import jso ...
- GOF对Builder模式的定义(转载)
(1)意图 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示. (2)适用性 1. 当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式:2. 当构造过程必须允许构 ...
- linux 流量控制全攻略(TC)
TC很是强大啊,很多所谓的硬件路由器,都是基于这个做的. TC介绍 在linux中,TC有二种控制方法CBQ和HTB.HTB是设计用来替换CBQ的.它是一个层次式的过滤框架.TC包括三个基本的构成块: ...
- GetLastError 错误码大全(转载)
转载自:GetLastError GetLastError GetLastError返回的值通过在api函数中调用SetLastError或SetLastErrorEx设置.函数 并无必要设置上一 ...
- <unistd.h>的close(0)导致std::cout被关闭
代码如下:其中ZJ::open_max返回系统允许的打开的文件的最大个数 #include "util.h" #include <unistd.h> // int cl ...