简体   繁体   English

MongoDB 从 Object.class 获取 ObjectID

[英]MongoDB get ObjectID from Object.class

I have a object class:我有一个对象类:

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(
    collection = "users"
)

public class UsersData {
    @Field("Name")
    private String name;
    @Field("Address")
    private Address address;

}

Users are fetched using the find(Query query,<T> entityClass) operation and mapped onto UserData.class使用find(Query query,<T> entityClass)操作获取用户并映射到 UserData.class

Is there any way to get the objectID of the document representing a User.有什么方法可以获取代表用户的文档的 objectID。 (I am unable to edit UserData.java as it is a readonly file) (我无法编辑 UserData.java,因为它是只读文件)

you can use type String or ObjectId您可以使用类型StringObjectId

public class UsersDataWithId extends UsersData {
    @Id
    private String id;
}

in alternative you can use Document type from MongoDB driver或者,您可以使用 MongoDB 驱动程序中的Document类型

MongoCollection<Document> collection = database.getCollection("users");
Document myDoc = collection.find().first();
myDoc.get("_id")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM