NoSql之MongoDB的常用类管理(三)

2014-11-24 11:51:58 · 作者: · 浏览: 1
ursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}
}
5、索引管理
[java]
package com.boonya.mongo;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
public class IndexManager {
private static DBCollection coll= CollectionManager.getDbCollection("myCollection");
public void createIndex(){
// create index on "i", ascending
coll.createIndex(new BasicDBObject("i", 1));
}
public List getIndexList(){
List list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
list.add(o);
}
return list;
}
}
6、预读取机制
[java]
package com.boonya.mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.ReadPreference;
public class ReadPreferences {
private static DBCollection coll= CollectionManager.getDbCollection("myCollection");
/**
* ReadPreference.primary();
* ReadPreference.primaryPreferred();
* ReadPreference.secondary();
* ReadPreference.secondaryPreferred();
* ReadPreference.nearest();
*/
public void read(){
DBObject query = new BasicDBObject("name", "simple doc");
//Read from primary if available, otherwise a secondary.
ReadPreference preference = ReadPreference.primaryPreferred();
DBCursor cur = new DBCursor(coll, query, (DBObject) preference);
//Read from any member node from the set of nodes which respond the fastest.
//The responsiveness of a node is measured with pings. Any node whose ping
//time is within 15 milliseconds of the node with the lowest ping time is considered near.
DBObject result =coll.findOne(query, (DBObject) ReadPreference.nearest());
// initialize a properly tagged read preference
ReadPreference tagged_pref =ReadPreference.secondaryPreferred(new BasicDBObject("datacenter", "Los Angeles"));
// include the tagged read preference in this request}}
DBObject result1=coll.findOne(new BasicDBObject("name", "simple doc"), (DBObject) tagged_pref);
// read from either LA or US_West
DBObject tagSetOne = new BasicDBObject("datacenter", "Los Angeles");
DBObject tagSetTwo = new BasicDBObject("region", "US_West");
ReadPreference pref =ReadPreference.primaryPreferred(tagSetOne, tagSetTwo);
}
}