如何使用 java 仅获取 mongodb 中文档的 objectId

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

我只想从 mongodb 中获取匹配的 objectId crieteria.I 可以使用 dbobject 和游标获取它 method.But 我在这里使用 mongo 客户端并且没有想法如何去做。 谢谢

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

使用 findOneAndUpdate,其中 returns Document 作为结果并映射 _id

类似

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

更新:包含 Projection 以将响应限制为仅包含 _id 字段。

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