3

I'm developing an application that create permalinks. I'm not sure how save the documents in MondoDB. Two strategies:

  1. ObjectId autogeneration

    MongoDB autogenerates the _id. I need to create an index on the permalink field because I get the information by the permalink. Also I can access to the creation time of the ObjectId, using the getTimestamp() method, so datetime fields seems to be redundant but if I delete this field I need two calls to MongoDB one to take the information and another to take the timestamp.

    {
      "_id": ObjectId("5210a64f846cb004b5000001"),
      "permalink": "ca8W7mc0ZUx43bxTuSGN",
      "data": "a lot of stuff",
      "datetime": ISODate("2013-08-18T11:47:43.460+-100")
    }
    
  2. Generate _id

    I generate the _id with the permalink.

    {
      "_id": "ca8W7mc0ZUx43bxTuSGN",
      "data": "a lot of stuff",
      "datetime": ISODate("2013-08-18T11:47:43.460+-100")
    }
    

I not see any advantage to use ObjectIds. Am I missing something?

Mehraban
  • 3,164
  • 4
  • 37
  • 60
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
  • i don't see a real question ? the autogenerated _id has some nice informations in like the timestamp, so you won't need to store a datetime in a seperate field like you are doing currently. And by the way the _id is auto generated it guarantees uniqueness – Dukeatcoding Aug 18 '13 at 13:56

1 Answers1

6

ObjectIds are there for situations where you don't have a unique key for every document in a collection. They're unique, so you don't have to worry about conflicts and they shard reasonably well in large deployments without too much worry (they have they're pros and cons, read more here).

The ObjectId also contains the timestamp of the client where the ObjectId was generated (unless the DB server is configured to generate all keys). With that, as you noticed, you can use the time stamp to perform some date operations. However, if you plan on using the Aggregation Framework, you'll find that you can't use an ObjectId in any date operations currently (issue). If you want to use the AF, you'll need a second field that contains the date, unfortunately doubly storing it with the ObjectId's internal value.

If you can be assured that the _id you're generating is unique, then there's not much reason to use an ObjectId in your data structure.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143