xcorat
xcorat

Reputation: 1472

Using timestamp as mongodb _id?

I want to use MongoDB to store timeseries data, and think it would make things more sense to keep one unique indexed field that represent date-time. So the question is, can I really replace the automatic _id creation with my own timestamp, and would there be any drawbacks?

Upvotes: 2

Views: 345

Answers (2)

James Wahlin
James Wahlin

Reputation: 2821

You can definitely populate _id field with your own timestamp. The things to look out for are:

  1. _id is a unique index so you would have to be sure that no 2 documents shared a timestamp. If you can't guarantee this then it would not work.
  2. If you were to shard this collection, you may want to avoid using a timestamp as the shard key. If you were always writing data points with the current timestamp then you would find all of your writes would go to a single shard, rather than distributed evenly across shards.

Upvotes: 2

shx2
shx2

Reputation: 64378

can I really replace the automatic _id creation with my own timestamp?

Yes, you can.

would there be any drawbacks?

One is that you have to work for it, whereas the built in _id is, well, built in. Another one is that you're responsible to making sure your _id is indeed unique. Depending on your data frequency and the kind of timestamp you use, this may or may not be simple.

I'm not saying it's necessarily a bad idea. The advantages are clear, but, yes, there are drawbacks.

Upvotes: 2

Related Questions