1. 程式人生 > >java操作mongodb的例子

java操作mongodb的例子


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 埠預設為27017
		Mongo 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<=10
		cur = 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();
		// 移除整個collection
		dCollection.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;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "名字:" + 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;
	}

	@Override
	public 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;
		}
	}
}