如何使用java在mongodb中仅获取文档的objectId [英] How can I get only the objectId of document in mongodb using java

查看:49
本文介绍了如何使用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");

这篇关于如何使用java在mongodb中仅获取文档的objectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆