Search code examples
javamongodbmongodb-java

How can I get only the objectId of document in mongodb using java


I want to get only the objectId from mongodb with matched crieteria.I can get it with dbobject and cursor method.But I used mongo client here and have no idea how to do it. Thanking you

    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase database = client.getDatabase("baazaronline");
    MongoCollection<Document> collection = database
            .getCollection("Attribute");

    Bson filter = new Document("attcode", attcode);

    Bson newValue = new Document("DefautV", DefautV).append("IVSO", IVSO).append("UniqueV", UniqueV).append("ValuesR", ValuesR).append("Visiblename", Visiblename).append("citso", citso).append("values",values);
    Bson updateOperationDocument = new Document("$set", newValue);
    collection.updateOne(filter, updateOperationDocument);

    client.close();

Solution

  • Use findOneAndUpdate which returns the Document as result and map the _id.

    Something like

    ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument).get("_id", ObjectId.class);
    

    Update: Include Projection to limit the response to only contain _id field.

    FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions();
    findOneAndUpdateOptions.projection(Projections.include("_id"));
    ObjectId id  =  collection.findOneAndUpdate(filter, updateOperationDocument, findOneAndUpdateOptions).getObjectId("_id");