Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB get ObjectID from Object.class

Tags:

java

mongodb

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

Is there any way to get the objectID of the document representing a User. (I am unable to edit UserData.java as it is a readonly file)

like image 348
uniQ Avatar asked Feb 15 '26 12:02

uniQ


1 Answers

you can use type String or ObjectId

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

in alternative you can use Document type from MongoDB driver

MongoCollection<Document> collection = database.getCollection("users");
Document myDoc = collection.find().first();
myDoc.get("_id")
like image 133
Aymen Avatar answered Feb 18 '26 00:02

Aymen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!