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

*爱你&永不变心* 提交于 2021-02-07 03:37:44

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/43474680/how-can-i-get-only-the-objectid-of-document-in-mongodb-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!