【发布时间】:2015-07-27 15:20:12
【问题描述】:
在 RDMS 中,如果我必须执行“从 empid=100 的员工中选择 emp_name”。我会这样做,
String query = "Select emp_name from Employee where empid=100"
Statement stmt = DriverManager.getConnection(db, user, password).createStatement();
result = stmt.executeQuery(query);
我怎样才能在 MongoDB 中执行相同的操作,在该查询中得到类似“Employee.find({'empid:1000'},{emp_name:1})”的查询
目前这是我正在使用的代码,其中我必须分别编写“where”和“select”部分,我的意思是 dbObj(where) 和 projectdbObj(projecttion or select part)。
DBObject dbObj = (DBObject) JSON.parse("{'employee.empid':'1000'}");
DBObject projectdbObj = (DBObject) JSON.parse("{'emp_name':1}");
try{
MongoCollection<Document> coll = mongoClient.getDatabase("Company" ).getCollection("Employee");
FindIterable<Document> cursor = coll.find((Bson) dbObj).projection((Bson) projectdbObj);
cursor.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.print(document);
}
});
}
请帮助优化代码。
【问题讨论】:
标签: json mongodb mongodb-query mongodb-java mongo-java-driver