Section 13.1: 使用条件获取集合数据
要从 testdb 数据库中的 testcollection 集合获取数据,其中 name=dev
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
MongoDatabase db = mongoClient.getDatabase("testdb");
MongoCollection<Document> collection = db.getCollection("testcollection");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name","dev");
MongoCursor<Document> cursor = collection.find(searchQuery).iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
Section 13.2: 创建数据库用户
创建用户 dev,密码为 password123
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("testDB");
Map<String, Object> commandArguments = new BasicDBObject();
commandArguments.put("createUser", "dev");
commandArguments.put("pwd", "password123");
String[] roles = { "readWrite" };
commandArguments.put("roles", roles);
BasicDBObject command = new BasicDBObject(commandArguments);
db.runCommand(command);
Section 13.3: 创建可跟踪游标
find(query).projection(fields).cursorType(CursorType.TailableAwait).iterator();
该代码适用于 MongoCollection 类。
CursorType 是一个枚举,有以下值:
Tailable
TailableAwait
对应于旧的(<3.0)DBCursor addOption Bytes 类型:
Bytes.QUERYOPTION_TAILABLE
Bytes.QUERYOPTION_AWAITDATA