假设我只想查询所有文档的某个属性,例如SQL:
SELECT FIRSTNAME
FROM TABLE1
我如何使用Mongo及其Java API?
答案 0 :(得分:2)
如果要获取所有文档,请使用 empty 对象作为第一个参数。使用第二个,您只能获得字段FIRSTNAME
。
db.table1.find({}, {'FIRSTNAME': 1});
有关详细信息,请参阅documentation on querying。
答案 1 :(得分:1)
在Java API中,您可以这样做。您必须明确关闭_id字段才能将其排除。
Mongo m = new Mongo();
DB db = m.getDB( "test" );
DBCollection coll = db.getCollection("test");
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
DBCursor curs = coll.find(query, fields);
while(curs.hasNext()) {
DBObject o = curs.next();
System.out.println(o.toString());
}
输出:
{ "Name" : "Wes"}
排序更新:
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Alex").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Zeus").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
BasicDBObject orderBy = new BasicDBObject("Name",1);
DBCursor curs = coll.find(query, fields).sort(orderBy);
while(curs.hasNext()) {
DBObject o = curs.next();
System.out.println(o.toString());
}
给出:
{ "Name" : "Alex"}
{ "Name" : "Wes"}
{ "Name" : "Zeus"}