lucheng918的个人博客分享 http://blog.sciencenet.cn/u/lucheng918

博文

java 连接 mongo

已有 3395 次阅读 2014-2-19 09:24 |个人分类:linux+oracle|系统分类:科研笔记| mongo

public static void getFileNameTmp(String inFile, String outFile){

try{

//连接数据库,链接  http://192.168.12.53/rockmongo/index.php?action=admin.index

Mongo m = new Mongo("192.168.12.53",27017);//服务器的名字,端口号

//方法1

DB db = m.getDB("RESUME");//指定要连接的数据库

//显示该数据库中的所有表名

Set<String> tables = db.getCollectionNames();

for(String s:tables){

//System.out.println(s);

}

//连接一个表

DBCollection coll = db.getCollection("text");//建立一个表的连接,如果该表不存在,则新建

List<String> result = new ArrayList<String>();

List<String> resultText = new ArrayList<String>();

//String wPath = "D:/projects/gongkong/title.txt";

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8")));   //用来修正编码问题,用于向txt输出

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile)));

String idStr = null;

while((idStr = br.readLine())!=null){

//System.out.println(idStr);

BasicDBObject query = new BasicDBObject();

ObjectId objId = new ObjectId(idStr);

query.put("_id", objId);    //MongoDB的正常操作方式,先通过_id定位

DBCursor cursor = coll.find(query);       //执行查询,找到一个数据集合

//System.out.println("cursor size: " + cursor.size());

DBObject dbobj = cursor.next();

Object fileNameObj = dbobj.get("fileName");            //然后根据key:filename找到相应的value

String fileName = fileNameObj.toString();

String fileText = dbobj.get("text").toString();

result.add(fileName);

resultText.add(fileText);

}

for(int i = 0; i < result.size(); i++){

out.write(result.get(i));

out.write("$");

out.write(resultText.get(i));

out.println();

out.flush();

}

//for(String str:result){

// //System.out.println(str);

// bw.write(str);

// bw.newLine();

// bw.flush();

//}

bw.close();

}catch(Exception e){

e.printStackTrace();

}

 

}



@Test

public void testDebugServiceGetFileName(){

DebugService.getFileNameTmp("D:/projects/gongkong/java_id.txt", "D:/projects/gongkong/java_filename.txt");

}


总结:mongoDB是以key-value的形式存储数据的,

  1. /* id 

  2.    每个MongoDB文档都必须有一个叫作"_id"的Key, 同一集合里面的文档_id必须各不相同。 

  3.    id可以在创建文档的时候指定,可以是任何类型,无指定时,默认使用ObjectId对象,自动生成不同的id。 

  4.  

  5.    ObjectId对象生成id(12位)的规则如下: 

  6.        0-3 : Timestamp,时间撮 

  7.        4-6  :  Machine,机器代码 

  8.        7-8  :  PID,MongoDB的程序id 

  9.        9-11:  Increment,一个自增量 

  10. */  

因此,如果想获取其中的值,需要通过_id找到该数据,然后通过相应的key找到value。



https://wap.sciencenet.cn/blog-780964-768805.html

上一篇:SQL of Oracle
下一篇:shell awk cut join sort
收藏 IP: 168.160.22.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-6-3 18:26

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部