ct;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;
/**
* function: 实现MongoDB的Index操作
* @author hoojo
* @createDate 2011-6-2 下午03:21:23
* @file MongoDB4IndexTest.java
* @package com.hoo.test
* @project MongoDB
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class MongoDB4IndexTest {
private Mongo mg = null;
private DB db;
private DBCollection users;
@Before
public void init() {
try {
mg = new Mongo();
//mg = new Mongo("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
//获取temp DB;如果默认没有创建,mongodb会自动创建
db = mg.getDB("temp");
//获取users DBCollection;如果默认没有创建,mongodb会自动创建
users = db.getCollection("users");
}
@After
public void destory() {
if (mg != null)
mg.close();
mg = null;
db = null;
users = null;
System.gc();
}
public void print(Object o) {
System.out.println(o);
}
}
3、 下面完成对象Collection的index的操作
/**
* function: 测试Collection的index相关操作
* @author hoojo
* @createDate 2012-2-16 下午08:32:26
*/
@Test
public void testIndex() {
query();
for (DBObject index : coll.getIndexInfo()) {
print("IndexInfo: " + index);
}
coll.dropIndexes();
//创建索引
coll.createIndex(new BasicDBObject("name", "idx_name"));
print(coll.findOne(new BasicDBObject("name", "haha")));
coll.createIndex(coll.findOne(new BasicDBObject("name", "haha")));
DBObject o = new BasicDBObject("unique", true);
//coll.createIndex(coll.findOne(), o);
// 修改索引,如果存在就修改不存在就添加
coll.ensureIndex(o);
coll.ensureIndex("age_1");
coll.ensureIndex(new BasicDBObject("age3_1", 6), new BasicDBObject("ts", -1));
coll.ensureIndex(new BasicDBObject("age_2", 1), new BasicDBObject( "ts" , 1 ));
coll.ensureIndex(new BasicDBObject("password", 2), new BasicDBObject( "z" , "idx" ));
coll.ensureIndex(new BasicDBObject("password", 1), new BasicDBObject( "etc" , "idx" ));
// 创建唯一索引
coll.ensureIndex(new BasicDBObject("emial", 2), new BasicDBObject("unique", false));
// 创建索引,指定索引名称default_index
coll.ensureIndex(new BasicDBObject("address", 1), new BasicDBObject( "name" , "default_index"));
// 创建索引对象,索引名称user_index
coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hoho")), "user_index");
// 唯一索引
coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hehe")), "users_index_unique", true);
// 查询所有索引
for (DBObject index : coll.getIndexInfo()) {
print("IndexInfo: " + index);
}
print(DBCollection.genIndexName(coll.findOne()));
//coll.dropIndex(coll.findOne());
print(DBCollection.genIndexName(new BasicDBObject("password", 2)));
//coll.dropIndex(DBCollection.genIndexName(new BasicDBObject("password", 2)));
//coll.dropIndexes();
//coll.dropIndexes("assword_1");
}
三、Morphia基本操作
1、morphia可以利用annotation对JavaEntity进行注解,那样我们就可以用morphia操作JavaEntity对象
package |