Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store reference to other collection in MongoDb [duplicate]

Tags:

mongodb

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

like image 643
Arūnas Smaliukas Avatar asked Mar 17 '23 08:03

Arūnas Smaliukas


1 Answers

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.

like image 53
ReneWeb Avatar answered Mar 20 '23 14:03

ReneWeb