如何使用java在mongodb中仅获取文档的objectId
问题描述:
我只想从具有匹配条件的 mongodb 中获取 objectId.我可以使用 dbobject 和 cursor 方法获取它.但是我在这里使用了 mongo 客户端,但不知道该怎么做.谢谢你
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();
答
使用 findOneAndUpdate
返回 Document
作为结果并映射 _id
.
Use findOneAndUpdate
which returns the Document
as result and map the _id
.
类似的东西
ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument).get("_id", ObjectId.class);
更新:包含 Projection
以将响应限制为仅包含 _id 字段.
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");