Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If i have a mongo document id as a string how do I query for it as an _id?

If i have a mongo document id as a string how do I query for it as an _id?

Will it work correctly to do .find({_id:'stringID'}) or do I need to convert it to a bson object first?

like image 914
fancy Avatar asked Apr 20 '12 21:04

fancy


People also ask

Can _id be a string MongoDB?

Yes, you can. BTW, uniqueness guaranteed by mongodb. Because _id field has a unique index by default.

How do I query a document in MongoDB?

To query data from MongoDB collection, you need to use MongoDB's find() method.

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

How do you check if a string is a valid Mongo ID?

Mongoose & MongoDB provide a very useful function in ObjectId i.e. ObjectId. isValid(“some_id”) to validate a string for correct MongoDB ID.


2 Answers

If your _id values are strings, you may query them just like any other field. (Just remember, if you are setting custom values for _id, they must be kept unique, or you will get a duplicate key error. )

Here is an example in the Mongo JS Shell:

> db.test.insert({_id:"stringID1"})
> db.test.insert({_id:"stringID2"})
> db.test.insert({_id:"stringID3"})
> db.test.find({_id:"stringID1"})
{ "_id" : "stringID1" }
> 

Is this what you were looking for? I hope I did not misunderstand your question!

like image 51
Marc Avatar answered Sep 19 '22 04:09

Marc


Mongoose auto casts the string _id to ObjectId when you use findByID, so you can query using the string _id.

Also remember that any input coming into your API from req.body or req.params will all be type string so you will need to type cast if needed..., but as mentioned, mongoose does that for you so you can just leave _id in the string format it comes in as.

like image 22
Paul OConnell Avatar answered Sep 20 '22 04:09

Paul OConnell