原文:分享哈我测试MongoDB数据库的简单代码
源代码下载地址:http://www.zuidaima.com/share/1550463424236544.htm
?
分布式文件存储系统,MongoDB部署安装具体可以参照:
http://www.cnblogs.com/mecity/archive/2011/06/11/2078527.html
Demo实现了从txt文件中逐行读取数据,存放到MongoDB数据库中的。
可参照其它Demo代码
这是一套基于Spring, Hibernate, Spring Data, Akka, Twitter Bootstrap, Apache Tiles, jQuery的简单案例源码
http://www.zuidaima.com/share/1550463264246784.htm
分享java操作mongodb的crud代码
代码中包括了mongodb的crud及其分页查询,排序功能
http://www.zuidaima.com/share/1550463230446592.htm
class="java" name="code">package com.zuidaima.pb.test; /** * 测试MongoDB数据库中查询所花费的时间(ms) * @author zoe www.zuidaima.com * date 2012-12-26 */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.net.UnknownHostException; import java.util.regex.Pattern; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; public class MyMongoDB { /* * get DBCollction * @return */ public static DBCollection getcoll() { Mongo mongo; try { mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("working"); DBCollection coll = db.getCollection("mytest"); return coll; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * 该方法是把txt文件中的数据,逐行存入到MongoDB数据库中 * 且每行中的数据只放入了一个字段中,若果是一行中的数据要放入多个字段中的话,还没有验证 */ public static void add() { String url = "d:/file.txt"; try { FileReader read = new FileReader(new File(url)); BufferedReader br = new BufferedReader(read); StringBuffer sbf = new StringBuffer(""); String line = null; int i = 0; DBCollection coll = getcoll(); while ((line = br.readLine()) != null) { coll.insert(new BasicDBObject().append("name", line).append( "no", i++)); } System.out.println(coll.getCount()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 无索引查询 */ public static void query() { DBCollection coll=getcoll(); BasicDBObject cond = new BasicDBObject(); Pattern pattern = Pattern.compile("浙江.*$"); long a = System.currentTimeMillis(); cond.put("name", pattern); // cond.put("name","宁海中通电子科技有限公司" ); DBCursor returns = coll.find(cond); int i = 0; while (returns.hasNext() && (++i < 25)) { System.out.println(returns.next()); } long b = System.currentTimeMillis(); System.out.println("所用时间 " + (b - a) + "毫秒"); } public static void main(String[] args) { query(); } }
?