Mongodb Java - 如何使用 find() 或 findOne() 返回受限字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6568910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongodb Java - How to return restricted fields with find() or findOne()
提问by kozher
With the driver Java Mongodb, I am looking for a way to return just restricted fields with a
find()
or findOne()
.
For example, I have a collection "people"
with fields : "id"
, "name"
, "surname"
, "address"
, "city"
... and I just want to return "name"
and "surname"
使用驱动程序 Java Mongodb,我正在寻找一种方法来仅返回带有find()
或的受限字段
findOne()
。例如,我有一个"people"
包含字段的集合:"id"
, "name"
, "surname"
, "address"
, "city"
... 我只想返回"name"
和"surname"
I searched on the Web and I just found this example of code Java Mongodb : http://vsbabu.org/mt/archives/2010/03/02/simple_mongodbjava_example.html
我在网上搜索,我刚刚找到了这个 Java Mongodb 代码示例:http://vsbabu.org/mt/archives/2010/03/02/simple_mongodbjava_example.html
采纳答案by lobster1234
You can pass another DBObject with the names of the fields and pass it here:
您可以传递另一个带有字段名称的 DBObject 并在此处传递:
cur = coll.find(new BasicDBObject("id", 6655), your_dbobject_with_field_names);
Here is the API documentation
这是API 文档
回答by seb
If you are using Java Driver 3.1, you can use Projections:
如果您使用的是 Java Driver 3.1,则可以使用Projections:
collection.find().projection(Projections.include("name", "surname"));
回答by G?khan Ayhan
This codes will handle your problem.(java driver 3.0.2)
此代码将处理您的问题。(java 驱动程序 3.0.2)
BasicDBObject fields = new BasicDBObject();
fields.put("title", 1);
DBCursor cursor = collection.find(new BasicDBObject(),fields).sort(new BasicDBObject("_id", 1));
回答by HungNM2
this code run for me:
这段代码为我运行:
String json = "{_id:0,name:1,surname:1}";
Bson bson = BasicDBObject.parse( json );
FindIterable<Document> iterDoc = collection.find().projection(bson);