查询MongoDB集合中的字段。 [英] Query fields in a MongoDB Collection.
本文介绍了查询MongoDB集合中的字段。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查询mongodb集合中的特定字段。这是我的代码和输出:
I am trying to query specific fields in a mongodb collection. Here is my code and output:
Mongo m = new Mongo();
DB db = m.getDB( "mydb" );
DBCollection coll = db.getCollection("student") ;
// adding data
BasicDBObject moz = new BasicDBObject();
moz.put("Name", "Mozammil");
coll.insert(moz);
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
这将返回以下内容:
{ "_id" : { "$oid" : "4f5a4477c5e80f71ece56797"} , "Name" : "Mozammil"}
但是,我只想要Name部分。谷歌搜索,这应该做的工作。
However, i want only the Name part. Googling around, this should do the job.
DBCursor cursor = coll.find({}, {'Name':1});
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
但它不起作用。请帮忙?
But it is not working. Help please?
推荐答案
您可以通过光标使用get返回的文档来获取您要查找的字段。像这样:
You can use get on the returned document by the cursor to get the field you are looking for. Like this:
System.out.println(cursor.next().get("key"));
这篇关于查询MongoDB集合中的字段。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文