4

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

Arūnas Smaliukas
  • 3,231
  • 6
  • 27
  • 46

1 Answers1

7

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.

ReneWeb
  • 206
  • 3
  • 10