java操作mongodb的例子

来源:互联网 发布:如何成立软件工作室 编辑:程序博客网 时间:2024/06/02 02:14


mongodb for  java的驱动下载:

https://github.com/mongodb/mongo-java-driver/downloads


package org.senssic.mongodb;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;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.Mongo;import com.mongodb.util.JSON;public class MongoTest {public static void main(String[] args) throws Exception {// 链接一台服务器// Mongo mongo=new Mongo();//默认连本机127.0.0.1 端口为27017// Mongo mongo=new Mongo("127.0.0.1");//可以指定ip 端口默认为27017Mongo mg = new Mongo("127.0.0.1", 27017);// 也可以指定ip及端口号// 链接多台服务器 Replication 同步数据缓解压力主从集群// List<ServerAddress> mongoHostList = new ArrayList<ServerAddress>();// mongoHostList.add(new ServerAddress("ip", port));// mongoHostList.add(new ServerAddress("ip", port));// mongoHostList.add(new ServerAddress("ip", port));// Mongo mg = new Mongo(mongoHostList);DB db = mg.getDB("test");// 链接数据库,无则创建// 如果添加安全则需要验证// boolean auth=db.authenticate("username", "password".toCharArray());// if (auth) {// //// }// 1.获取数据库信息// 获取所有数据库List<String> list = mg.getDatabaseNames();for (String string : list) {System.out.println(string);}// 获取所有集合Set<String> set = db.getCollectionNames();for (String string : set) {System.out.println(string);}// 获得集合 没有的话自动创建也可以使用下一个方法创建DBCollection dCollection = db.getCollection("sen");// 如果不存在就创建if (!db.collectionExists("temp")) {DBObject options = new BasicDBObject();options.put("size", 20);options.put("capped", 20);options.put("max", 20);System.out.println(db.createCollection("account", options));}// 2.添加操作// 第一种方式 最常用DBObject dbObject = new BasicDBObject();dbObject.put("_id", Tools.getNext(dCollection, "sen"));dbObject.put("name", "sen");dbObject.put("age", 21);dbObject.put("date", new Date());dCollection.save(dbObject);// dCollection.insert(dbObject);// 第二种方式BasicDBObjectBuilder b = BasicDBObjectBuilder.start();b.add("_id", Tools.getNext(dCollection, "sen"));b.add("name", "qiyu");b.add("date", new Date());dCollection.save(b.get());// dCollection.insert(b.get());// 第三种方式String json = "{'_id':" + Tools.getNext(dCollection, "sen")+ ",'name':'senssic','age':22,'date':" + "'"+ new Date().toString() + "'}";dbObject = (DBObject) JSON.parse(json);dCollection.save(dbObject);// 3.查询操作// 查询集合中所有数据DBCursor cur = dCollection.find();while (cur.hasNext()) {System.out.println(cur.next());}System.out.println(cur.count());System.out.println(cur.getCursorId());System.out.println(JSON.serialize(cur));// 根据条件查询where _id=12 条件查询集合查询等和操作数据库差不多可以看下mongodb的数据库操作语法cur = dCollection.find(new BasicDBObject("_id", 12));while (cur.hasNext()) {System.out.println(cur.next());}// 查询_id>3 且只取5条cur = dCollection.find(new BasicDBObject("_id", new BasicDBObject("$gte", 3))).limit(5);while (cur.hasNext()) {System.out.println(cur.next());}// 查询id大于3且id降序 -1降序 1升序cur = dCollection.find(new BasicDBObject("_id", new BasicDBObject("$gte", 3))).sort(new BasicDBObject("_id", -1));while (cur.hasNext()) {System.out.println(cur.next());}// 查询id大于等于1的记录,跳过前5条记录并且只显示5条记录。相当// 于分页功能where id>5 and id<=10cur = dCollection.find(new BasicDBObject("_id", new BasicDBObject("$gte", 1))).skip(5).limit(5);while (cur.hasNext()) {System.out.println(cur.next());}// 返回>1的记录条数System.out.println(dCollection.find(new BasicDBObject("_id", new BasicDBObject("$gte", 1))).count());// 查询一条数据@SuppressWarnings("unchecked")Map<String, Object> map = dCollection.findOne().toMap();for (Entry<String, Object> entry : map.entrySet()) {System.out.println(entry.getKey() + "--->" + entry.getValue());}// dCollection.findOne(new BasicDBObject("_id",12));// dCollection.findOne(new BasicDBObject("_id", 12), new BasicDBObject(// "name", true));// 返回_id和name的值// 查询并删除dCollection.findAndRemove(new BasicDBObject("_id", 12));// 查询并修改dCollection.findAndModify(new BasicDBObject("_id", 10), // 查询_id=28的数据new BasicDBObject("name", true), // 查询name属性new BasicDBObject("age", true), // 按照age排序false, // 查询到的记录是否删除,true表示删除new BasicDBObject("date", new Date()), // 将date的值改为当前时间true, // 是否返回新记录 true返回,false不返回true // 如果没有查询到该数据是否插collection true入库,false不入);// 4.更新// 替换更新 讲查找到的记录覆盖更新System.out.println(dCollection.update(new BasicDBObject("_id", 10),new BasicDBObject("city", "hefei")).getN());// 局部更新 只是更新选定的字段,并不会覆盖更新System.out.println(dCollection.update(new BasicDBObject("_id", 3),new BasicDBObject("$set", new BasicDBObject("city","chizhou")), false, // 如果数据库不存在,是否添加true // 多条修改,false只修改一条记录).getN());// 5.删除dCollection.remove(new BasicDBObject("_id", "5")).getN();// 移除id>=1的数据dCollection.remove(new BasicDBObject("_id", new BasicDBObject("$gte", 20))).getN();// 移除整个collectiondCollection.drop();}private static final class Tools {// 实现mongodb主键自增长的功能,原理在数据库中插入一条当前记录数据{ "_id" : "sen", "next" : 12 }public static long getNext(DBCollection users, String tableName) {long incId = 0;try {DBObject ret = users.findAndModify(new BasicDBObject("_id",tableName), null, null, false, new BasicDBObject("$inc", new BasicDBObject("next", 1)), true, true);incId = Long.valueOf(ret.get("next").toString());} catch (Exception e) {e.printStackTrace();}return incId;}}}


保存java对象  保存文件

package org.senssic.mongodb;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;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.gridfs.GridFS;import com.mongodb.gridfs.GridFSDBFile;import com.mongodb.gridfs.GridFSInputFile;class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;private List<String> hobbys;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public List<String> getHobbys() {return hobbys;}public void setHobbys(List<String> hobbys) {this.hobbys = hobbys;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "名字:" + this.name + "--->年龄:" + this.age;}}public class MongoF {public static void main(String[] args) throws Exception {Mongo mg = new Mongo();DB db = mg.getDB("test");DBCollection dCollection = db.getCollection("sen");Person person = new Person();person.setName("sensen");person.setAge(20);List<String> list = new ArrayList<>();list.add("足球");list.add("乒乓球");person.setHobbys(list);// 1.存储java对象// 存储对象方式一 通过序列化存二进制// 存DBObject dbo = new BasicDBObject();ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ObjectOutputStream out = new ObjectOutputStream(outputStream);out.writeObject(person);dbo.put("JavaObject", outputStream.toByteArray());dbo.put("name", "objboj");out.close();outputStream.close();dCollection.insert(dbo);// 读DBObject object = dCollection.findOne(new BasicDBObject("name","objboj"));byte[] javaObjectByte = (byte[]) object.get("JavaObject");InputStream inputStream = new ByteArrayInputStream(javaObjectByte);ObjectInputStream in = new ObjectInputStream(inputStream);Person javaObject = (Person) in.readObject();System.out.println(javaObject.toString());in.close();inputStream.close();// 2.通过将字段和DBObject相互转换来操作存储person = new Person();person.setName("aaaaaaaaaaaaaaaaaaaaaaaaaa");person.setAge(100);List<String> lStrings = new ArrayList<>();lStrings.add("faasdfa");lStrings.add("ffffff");person.setHobbys(lStrings);dCollection.save(BasicDBObjectUtils.castModel2DBObject(person));// 3.存放文件 如果存个大文件很慢哦// 存File f = new File("D://workspace//jar//morphia-0.99.jar");GridFS myFS = new GridFS(db);GridFSInputFile inputFile = myFS.createFile(f);inputFile.save();DBCursor cursor = myFS.getFileList();while (cursor.hasNext()) {System.out.println(cursor.next());}// 读f = new File("d://temp.jar");GridFS fs = new GridFS(db);GridFSDBFile dFile = fs.find("mongodb-win32-i386-2.4.10.zip").get(0);dFile.writeTo(f);mg.close();}private static class BasicDBObjectUtils {public static <T> DBObject castModel2DBObject(T entity)throws Exception {Method[] method = entity.getClass().getMethods();DBObject dbObject = new BasicDBObject();for (Method m : method) {if (m.getName().startsWith("get")) {String name = m.getName().replace("get", "");for (Method m2 : method) {if (m2.getName().equals("set" + name)) {name = name.substring(0, 1).toLowerCase()+ name.substring(1);Object returnVal = m.invoke(entity, new Object[] {});if (returnVal != null) {dbObject.put(name, returnVal);}}}}}System.out.println("dbObject: " + dbObject);return dbObject;}}}


保存java对象升级版(只支持简单的list set map类型不支持深度的集合,且集合里只能存放基础数据):

package org.senssic.mongodb;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.bson.types.ObjectId;import com.mongodb.BasicDBList;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.Mongo;class Person {private ObjectId _id;private String name;private int age;private Map<String, String> map;private Set<String> set;private List<String> hobbys;public ObjectId get_id() {return _id;}public void set_id(ObjectId _id) {this._id = _id;}public Map<String, String> getMap() {return map;}public void setMap(Map<String, String> map) {this.map = map;}public Set<String> getSet() {return set;}public void setSet(Set<String> set) {this.set = set;}public List<String> getHobbys() {return hobbys;}public void setHobbys(List<String> hobbys) {this.hobbys = hobbys;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "id:" + this._id + "名字:" + this.name + "--->年龄:" + this.age+ "---" + this.hobbys + this.set + this.map;}}public class MongoF {public static void main(String[] args) throws Exception {Mongo mg = new Mongo();DB db = mg.getDB("test");DBCollection dCollection = db.getCollection("sen");Person person = new Person();person.setName("sensen");person.setAge(20);List<String> lStrings = new ArrayList<>();lStrings.add("faasdfa");lStrings.add("ffffff");Map<String, String> mp = new HashMap<>();mp.put("aaa", "aaaffff");mp.put("bbb", "bbbf");Set<String> set = new HashSet<>();set.add("ffffffffffffffffffaaaaaaaaaaaaaa");set.add("setset");person.setSet(set);person.setMap(mp);person.setHobbys(lStrings);dCollection.save(BasicDBObjectUtils.castModel2DBObject(person));// 保存java实体Person person2 = BasicDBObjectUtils.castDBObject2Model(Person.class,dCollection.findOne());// 转换java实体System.out.println(person2.toString());}private static class BasicDBObjectUtils {public static <T> DBObject castModel2DBObject(T entity)throws Exception {Method[] method = entity.getClass().getMethods();DBObject dbObject = new BasicDBObject();for (Method m : method) {if (m.getName().startsWith("get")) {String name = m.getName().replace("get", "");for (Method m2 : method) {if (m2.getName().equals("set" + name)) {name = name.substring(0, 1).toLowerCase()+ name.substring(1);Object returnVal = m.invoke(entity, new Object[] {});if (returnVal != null) {dbObject.put(name, returnVal);}}}}}return dbObject;}@SuppressWarnings({ "unchecked", "rawtypes" })public static <T> T castDBObject2Model(Class<T> czlss, DBObject dbObject)throws Exception {T t = czlss.newInstance();Method[] methods = czlss.getMethods();Map<String, Object> map = dbObject.toMap();for (Entry<String, Object> entry : map.entrySet()) {if (entry.getValue() instanceof BasicDBList) {BasicDBList bList = (BasicDBList) entry.getValue();Iterator<Object> i = bList.iterator();Collection<Object> list = new ArrayList<>();Collection<Object> set = new HashSet<>();while (i.hasNext()) {list.add(i.next());set.add(i.next());}String key = entry.getKey();key = "set"+ key.replaceFirst(key.substring(0, 1), key.substring(0, 1).toUpperCase());for (Method method : methods) {if (method.getName().equals(key)) {Class[] c = method.getParameterTypes();if (c[0].getName().equals(Set.class.getName())) {method.invoke(t, set);} else {method.invoke(t, list);}}}} else if (entry.getValue() instanceof BasicDBObject) {BasicDBObject bObject = (BasicDBObject) entry.getValue();Map<String, Object> mp = new HashMap<>();Set<String> kSet = bObject.keySet();for (String string : kSet) {mp.put(string, bObject.get(string));}String key = entry.getKey();key = "set"+ key.replaceFirst(key.substring(0, 1), key.substring(0, 1).toUpperCase());for (Method method : methods) {if (method.getName().equals(key)) {method.invoke(t, mp);}}} else {String key = entry.getKey();key = "set"+ key.replaceFirst(key.substring(0, 1), key.substring(0, 1).toUpperCase());for (Method method : methods) {if (method.getName().equals(key)) {System.out.println(key);method.invoke(t, entry.getValue());}}}}return t;}}}




0 0