简体   繁体   中英

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 . 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. 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.

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. 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 静态导入包

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:

Document = db.getCollection("User").find(filter).first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM