ITKeyword,专注技术干货聚合推荐

注册 | 登录

java操作mongodb

相关推荐:Mongodb3.0.5副本集搭建及spring和java连接副本集配置

这是去年写的一篇文档,最近突然发现并没有发不出来,因此现在补上,希望能对某些朋友有所帮助。因为当时记录时没有截图,因此这里看起来可能就比较单调。一、基

首先下载驱动:http://download.csdn.net/detail/q383965374/6209691官网下载驱动:https://github.com/mongodb/mongo-java-driver/downloads驱动源码下载:https://codeload.github.com/mongodb/mongo-java-driver/zip/master在线查看源码:https://github.com/mongodb/mongo-java-driver对mongodb的操作主要还是 增删改查本文的内容:1.引用驱动2.添加命名空间3.连接数据库4.插入5.查询6.修改7.删除8.增删改查完整代码9.可能用到的用法10.mapreduce的用法完整代码1.引用驱动把下载的驱动jar放到工程中 引用:2.添加命名空间使用mongoDB需要导入以下类,当然不是全部需要,用到的类就导入。(也可以用到的时候再导入)import com.mongodb.Mongo;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.BasicDBObject;import com.mongodb.DBObject;import com.mongodb.DBCursor;import com.mongodb.ObjectId;3.连接数据库Mongo mg=new Mongo("192.168.0.121",27017);

DB db = mg.getDB("test"); //相当于库名

DBCollection coll = db.getCollection("Student");//相当于表名4.插入//插入数据(批量插入)

insert(coll);private static void insert(DBCollection coll) {

List<DBObject> datas = new ArrayList<DBObject>();

for (int i=0; i < 100; i++) {

BasicDBObject bo = new BasicDBObject();

BasicDBObject xx = new BasicDBObject();

xx.put("sex", "man");

xx.put("habit", "basketball");

bo.put("name", "bruce");

bo.append("number", i);

bo.put("others", xx);

datas.add(bo);

}

coll.insert(datas);

System.out.print("插入ok"); }结果:5.查询 //查询

//查询所有

queryAll(coll);

//查询一条//

System.out.println(coll.findOne());

//加条件查询方法一//

System.out.println(coll.findOne(new BasicDBObject("number",4)));

//加条件查询方法二//

BasicDBObject condition = new BasicDBObject();//

condition.put("number",4); //

DBCursor cur = coll.find(condition);//

while(cur.hasNext()) {//

System.out.println(cur.next());//

}结果:6.修改//修改数据

System.out.println(coll.findOne(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45"))));

coll.update(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45")),new BasicDBObject("name","coco"));

coll.update(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45")),new BasicDBObject("name","coco"),true,true);

//第一个true代表没有该条数据时进行添加

//第二个true表示存在多条时只修改第一条,有多条时不修改.为false时,修改多条

System.out.println(coll.findOne(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45"))));结果:7.删除//删除

System.out.println(coll.findOne(new BasicDBObject("number",6)));

coll.findAndRemove(new BasicDBObject("number",6));

System.out.println(coll.findOne(new BasicDBObject("number",6)));

System.out.println(coll.findOne(new BasicDBObject("number",7)));

coll.remove(new BasicDBObject("number",7));

System.out.println(coll.findOne(new BasicDBObject("number",7)));结果:8.增删改查完整代码package Test;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.bson.types.ObjectId;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.Mongo;import com.mongodb.MongoException;public class TestMogodb { public static void main(String[] args) throws UnknownHostException,MongoException {

Mongo mg=new Mongo("192.168.0.121",27017);

DB db = mg.getDB("test"); //相当于库名

DBCollection coll = db.getCollection("Student");//相当于表名

//插入数据(批量插入)//

insert(coll);

//查询

//查询所有//

queryAll(coll);

//查询一条//

System.out.println(coll.findOne());

//加条件查询方法一//

System.out.println(coll.findOne(new BasicDBObject("number",4)));

//加条件查询方法二//

BasicDBObject condition = new BasicDBObject();//

condition.put("number",4); //

DBCursor cur = coll.find(condition);//

while(cur.hasNext()) {//

System.out.println(cur.next());//

}

//

//修改数据//

System.out.println(coll.findOne(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45"))));//

//

coll.update(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45")),new BasicDBObject("name","coco"));//

//

//coll.update(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45")),new BasicDBObject("name","coco"),true,true);//

//第一个true代表没有该条数据时进行添加//

//第二个true表示存在多条时只修改第一条,有多条时不修改.为false时,修改多条//

System.out.println(coll.findOne(new BasicDBObject("_id",new ObjectId("5226fd43789e1cfd2009ea45"))));

//删除

System.out.println(coll.findOne(new BasicDBObject("number",6)));

coll.findAndRemove(new BasicDBObject("number",6));

System.out.println(coll.findOne(new BasicDBObject("number",6)));

System.out.println(coll.findOne(new BasicDBObject("number",7)));

coll.remove(new BasicDBObject("number",7));

System.out.println(coll.findOne(new BasicDBObject("number",7)));

} private static void queryAll(DBCollection coll) {

DBCursor cur = coll.find();

while(cur.hasNext()) {

System.out.println(cur.next());

} } private static void insert(DBCollection coll) {

List<DBObject> datas = new ArrayList<DBObject>();

for (int i=0; i < 100; i++) {

BasicDBObject bo = new BasicDBObject();

BasicDBObject xx = new BasicDBObject();

xx.put("sex", "man");

xx.put("habit", "basketball");

bo.put("name", "bruce");

bo.append("number", i);

bo.put("others", xx);

datas.add(

相关推荐:用C#操作Mongodb(c#mongodb驱动)

MongoDB的C#驱动基于.Net 3.5的 必要用.net 3.5以上的框架1.对数据库的操作主要还是增删改查2.了解c#操作mapreduce的语法我们先布置驱动环境,再通

bo);

}

coll.insert(datas);

System.out.print("插入ok"); } }9.可能用到的用法类转换当把一个类对象存到mongoDB后,从mongoDB取出来时使用setObjectClass()将其转换回原来的类。public class Tweet implements DBObject {}Tweet myTweet = new Tweet();myTweet.put("user", "bruce");myTweet.put("message", "fun");myTweet.put("date", new Date());collection.insert(myTweet);//转换collection.setObjectClass(Tweet);Tweet myTweet = (Tweet)collection.findOne();默认ID当保存的对象没有设置ID时,mongoDB会默认给该条记录设置一个ID("_id")。当然你也可以设置自己指定的ID,如:(在mongoDB中执行用db.users.save({_id:1,name:'bruce'});)BasicDBObject bo = new BasicDBObject();bo.put('_id', 1);bo.put('name', 'bruce');collection.insert(bo);权限判断是否有mongoDB的访问权限,有就返回true,否则返回false。boolean auth = db.authenticate(myUserName, myPassword);查看mongoDB数据库列表Mongo m = new Mongo();for (String s : m.getDatabaseNames()) {System.out.println(s);}查看当前库下所有的表名,等于在mongoDB中执行show tables;Set<String> colls = db.getCollectionNames();for (String s : colls) {System.out.println(s);}查看一个表的索引List<DBObject> list = coll.getIndexInfo();for (DBObject o : list) {System.out.println(o);}删除一个数据库Mongo m = new Mongo();m.dropDatabase("myDatabaseName");建立mongoDB的链接Mongo m = new Mongo("localhost", 27017);DB db = m.getDB("myDatabaseName"); //相当于库名DBCollection coll = db.getCollection("myUsersTable");//相当于表名#查询数据查询第一条记录DBObject firstDoc = coll.findOne();findOne()返回一个记录,而find()返回的是DBCursor游标对象。查询全部数据DBCursor cur = coll.find();while(cur.hasNext()) {System.out.println(cur.next());}查询记录数量coll.find().count();coll.find(new BasicDBObject("age", 26)).count();设置条件查询BasicDBObject condition = new BasicDBObject();condition.put("name", "bruce");condition.put("age", 26);coll.find(condition);查询部分数据块DBCursor cursor = coll.find().skip(0).limit(10);while(cursor.hasNext()) {System.out.println(cursor.next());}比较查询(age > 50)BasicDBObject condition = new BasicDBObject();condition.put("age", new BasicDBObject("$gt", 50));coll.find(condition);比较符"$gt": 大于"$gte":大于等于"$lt": 小于"$lte":小于等于"$in": 包含//以下条件查询20<age<=30condition.put("age", new BasicDBObject("$gt", 20).append("$lte", 30));#插入数据批量插入List datas = new ArrayList();for (int i=0; i < 100; i++) {BasicDBObject bo = new BasicDBObject();bo.put("name", "bruce");bo.append("age", i);datas.add(bo);}coll.insert(datas);正则表达式查询所有名字匹配 /joh?n/i 的记录Pattern pattern = Pattern.compile("joh?n", CASE_INSENSITIVE);BasicDBObject query = new BasicDBObject("name", pattern);DBCursor cursor = coll.find(query);-----------------------------------------------------------------模糊查询:db.analytics.find({referer_url: /http:.*/i});db.analytics.find({start_time:{$gte:new Date(2010,5,28),$lt:new Date(2010,5,29)},referer_url:/http:.*/}).count()正则表达式查询所有名字匹配 /joh?n/i 的记录Pattern pattern = Pattern.compile("joh?n", CASE_INSENSITIVE);BasicDBObject query = new BasicDBObject("name", pattern);DBCursor cursor = coll.find(query);condition.put("name", "bruce");condition.put("age", 26);coll.find(condition);查询部分数据块DBCursor cursor = coll.find().skip(0).limit(10);while(cursor.hasNext()) {System.out.println(cursor.next());}比较查询(age > 50)BasicDBObject condition = new BasicDBObject();condition.put("age", new BasicDBObject("$gt", 50));coll.find(condition);比较符"$gt": 大于"$gte":大于等于"$lt": 小于"$lte":小于等于"$in": 包含//以下条件查询20<age<=30condition.put("age", new BasicDBObject("$gt", 20).append("$lte", 30));#插入数据批量插入List datas = new ArrayList();for (int i=0; i < 100; i++) {BasicDBObject bo = new BasicDBObject();bo.put("name", "bruce");bo.append("age", i);datas.add(bo);}coll.insert(datas);正则表达式查询所有名字匹配 /joh?n/i 的记录Pattern pattern = Pattern.compile("joh?n", CASE_INSENSITIVE);BasicDBObject query = new BasicDBObject("name", pattern);DBCursor cursor = coll.find(query);--------日期:db.cpc_common.cpc_click_log.find({date_created:{$gte:new Date(2010,5,16)}});---------------------------建立collection db.createCollection("mycoll", {size:10000000});----------索引:db.mycollection.ensureIndex( {active:1} );10.mapreduce的用法完整代码package Test;import com.mongodb.BasicDBObject;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBObject;

import com.mongodb.MapReduceCommand;

import com.mongodb.MapReduceOutput;

import com.mongodb.Mongo; public class catchMongo{

/**

* @param args

*/

public static void main(String[] args) {

Mongo mongo;

try {

mongo = new Mongo("192.168.0.121", 27017);

DB db = mongo.getDB("test");

DBCollection books = db.getCollection("Student");

String map = "function Map(){if(this.number=='0'){emit('result',this);}}";

String reduce = "function Reduce(key, values) {return values[0];}";

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) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

结果:

相关推荐:Java操作MongoDB增删改查完美Demo

——因为实习工作需要,在学MongoDB,参考了公司的一个MongDB服务类,写了一个整合的Demo,涉及到的大部分的增删改查操作,而且还算规范,给大家参考!源代码:

首先下载驱动:http://download.csdn.net/detail/q383965374/6209691官网下载驱动:https://github.com/mongodb/mongo-java-driver/downloads驱动源码下载:https://codeload.github...

相关阅读排行


用户评论

游客

相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。