[英]Return the Specified Fields and the _id Field Only in java
UPDATE: Spuggiehawk advised in his answer to fix the include
keyword issue, and also suggest an alternative way to get the _id
other than projections
.更新:Spuggiehawk 在他的回答中建议修复
include
关键字问题,并建议另一种方法来获取_id
而非projections
。 However, I still have trouble to call this method from my service class, which edit the user detail, that I must admit I have limited knowledge to make it right.但是,我仍然无法从编辑用户详细信息的服务类中调用此方法,我必须承认我的知识有限以使其正确。
@Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
User user = new User();
for (User doc : userTbl) {
String oid = doc.getId().toHexString();
System.out.println("_id = " + oid);
return user;
}
return null;
}
In the Service class在服务类
public void editUser() {
String userId = request.getParameter("id");
User user = userDAO.get(userId);
System.out.println(user.getFullName());
}
You don't need to use projection if you just want the object ID.如果您只需要对象 ID,则不需要使用投影。 The syntax you want to get that (in a loop) is:
您想要获得的语法(在循环中)是:
FindIterable<Document> userTbl = db.getCollection("User").find();
for (Document doc: userTbl2)
{
String id = doc.getObjectId("_id").toString();
System.out.println("_id = " + id);
}
Do what you need to with that id value.使用该 id 值执行您需要的操作。
As far as your use of include is concerned, if you do find a situation where you need that, then you need the static import.就您对 include 的使用而言,如果您确实发现需要它的情况,那么您需要静态导入。 Eclipse should give you the option if you hover over the keyword:
如果您将鼠标悬停在关键字上,Eclipse 应该为您提供选项:
If Eclipse doesn't show that, you might need to add the references in your Eclipse configuration under Window -> Preferences -> Java -> Editor -> Content Assist -> Favorites:如果 Eclipse 没有显示,您可能需要在 Eclipse 配置中的 Window -> Preferences -> Java -> Editor -> Content Assist -> Favorites 下添加引用:
The important part is at the top of your code, it should include:重要的部分是在你的代码的顶部,它应该包括:
import static com.mongodb.client.model.Projections.include;
You'll find that useful for your filters too, eg.你会发现这对你的过滤器也很有用,例如。
Bson filter = eq("email", "email.com");
db.getCollection("User").find(filter);
Finally, if you only want to get the first matching record in your find(), use:最后,如果您只想获取 find() 中的第一条匹配记录,请使用:
Document = db.getCollection("User").find(filter).first();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.