Search code examples
javamongodbcrudpojomap-projections

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());     
}

Solution

  • 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:

    Static import in 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 static import packages

    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();