日期:2014-05-16  浏览次数:20449 次

mongodb连接java

package com.mongo.ulit;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MonConnection {
??public static void main(String[] args) {
???try {??
???????????? //实例化Mongo对象,连接27017端口??
???????????? Mongo mongo = new Mongo("localhost", 27017);??
??????????? //连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立??
???????????? DB db = mongo.getDB("yourdb");??
???????????? // Get collection from MongoDB, database named "yourDB"??
???????????? //从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立??
???????????? DBCollection collection = db.getCollection("yourCollection");?
????????????
???????????? // 使用BasicDBObject对象创建一个mongodb的document,并给予赋值。??
???????????? BasicDBObject document = new BasicDBObject();?
????????????
????????????
???????????? document.put("id", 1001);??
???????????? document.put("msg", "hello world mongoDB in Java");?
????????????
???????????? //将新建立的document保存到collection中去??
???????????? collection.insert(document);??
???????????
???????????? // 创建要查询的document??
???????????? BasicDBObject searchQuery = new BasicDBObject();??
???????????? searchQuery.put("id", 1001);??
???????????? // 使用collection的find方法查找document??
???????????? DBCursor cursor = collection.find(searchQuery);??
???????????? //循环输出结果??
???????????? while (cursor.hasNext()) {??
???????????? System.out.println(cursor.next());??
???????????? }??
????????????
???????????? System.out.println("Done");???
???????? } catch (UnknownHostException e) {??
???????????? e.printStackTrace();??
???????? } catch (MongoException e) {??
???????????? e.printStackTrace();??
???????? }??

??}
}

?

?

下面是mongodb的java驱动jar文件

?

mongodb? 包,使用的时间将mongodb.z01.zip改为mongodb.z01然后解压即可

1 楼 leon709 2012-02-27  
我虽然知道在官网下载MongoDB很简单,但是现在公司的电脑上不能去下载。
不过在Iteye上赋的附件链接可以下载,楼主大哥能不能顺便把MongoDB的开发包都传上来一份啊?就像这个jar包一样。
2 楼 jose_bing 2012-03-02  
已上传完成,欢迎下载