I need to store reference to other collection and I can't decide if I should store it as a string, or as an ObjectId()
. I see it is possible do it in both ways (in mongo shell):
As an ObjectId
db.books.findOne({_id:ObjectId("54bc1287c582714e9f062591")});
{
"_id" : ObjectId("54bc1287c582714e9f062591"),
"title" : "Book title",
"author_id" : ObjectId("54bc12da5f5e8854718b4568")
}
As a string
db.books.findOne({_id:ObjectId("54bc1287c582714e9f062591")});
{
"_id" : ObjectId("54bc1287c582714e9f062591"),
"title" : "Book title",
"author_id" : "54bc12da5f5e8854718b4568"
}
I will not be searching by author_id
, so I don't need any index there. I'll take a book, and then will take an author by author_id
. By the way, it is just an example with books
The major difference is that an ObjectId will take up 12 bytes space (http://docs.mongodb.org/manual/reference/object-id/) while the string representation takes 24 bytes. Thus, using ObjectId's will save you half the space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With