![](/img/trans.png)
[英]Querying data in MongoDB-Java to remove _id and show only specified field
[英]Return the Specified Fields and the _id Field Only in java
更新:Spuggiehawk 在他的回答中建議修復include
關鍵字問題,並建議另一種方法來獲取_id
而非projections
。 但是,我仍然無法從編輯用戶詳細信息的服務類中調用此方法,我必須承認我的知識有限以使其正確。
@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;
}
在服務類
public void editUser() {
String userId = request.getParameter("id");
User user = userDAO.get(userId);
System.out.println(user.getFullName());
}
如果您只需要對象 ID,則不需要使用投影。 您想要獲得的語法(在循環中)是:
FindIterable<Document> userTbl = db.getCollection("User").find();
for (Document doc: userTbl2)
{
String id = doc.getObjectId("_id").toString();
System.out.println("_id = " + id);
}
使用該 id 值執行您需要的操作。
就您對 include 的使用而言,如果您確實發現需要它的情況,那么您需要靜態導入。 如果您將鼠標懸停在關鍵字上,Eclipse 應該為您提供選項:
如果 Eclipse 沒有顯示,您可能需要在 Eclipse 配置中的 Window -> Preferences -> Java -> Editor -> Content Assist -> Favorites 下添加引用:
重要的部分是在你的代碼的頂部,它應該包括:
import static com.mongodb.client.model.Projections.include;
你會發現這對你的過濾器也很有用,例如。
Bson filter = eq("email", "email.com");
db.getCollection("User").find(filter);
最后,如果您只想獲取 find() 中的第一條匹配記錄,請使用:
Document = db.getCollection("User").find(filter).first();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.