Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java String to ObjectId of mongodb _id using java programming language [duplicate]

e.g:

String hexString = "5afea3b5bc7f8d04fc61d525";

to an ObjectId like

ObjectId("5afea3b5bc7f8d04fc61d525")

Here the above string is obtained from objectId so while writing query in mongodb the _id of mongodb document doesnot match to the string.....Therefore how can i get the matched data from mongodb document by passing string as parameter from rest api to match that _id of mongodb document.

like image 601
sanjay Avatar asked May 18 '18 11:05

sanjay


People also ask

Can MongoDB _id be string?

Yes, you can use a string as your _id.

Can I use _id from MongoDB?

The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.

What is the type of ObjectId in MongoDB?

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.

What is ObjectId in Java?

ObjectId(java.util.Date date, int counter) Constructs a new instances using the given date and counter. ObjectId(java.util.Date date, int machineIdentifier, short processIdentifier, int counter) Constructs a new instances using the given date, machine identifier, process identifier, and counter.


1 Answers

Use:

ObjectId objId = new ObjectId("5afea3b5bc7f8d04fc61d525");

See more ObjectId constructor here

like image 76
Mạnh Quyết Nguyễn Avatar answered Oct 19 '22 06:10

Mạnh Quyết Nguyễn