Store enum MongoDB

后端 未结 1 440
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 22:42

I am storing enums for things such as ranks (administrator, moderator, user...) and achievements for each user in my Mongo database. As far as I know Mongo does not have an enum

1条回答
  •  走了就别回头了
    2021-02-06 23:10

    TL;DR: Strings are probably the safer choice, and the performance difference should be negligible. Integers make sense for huge collections where the enum must be indexed. YMMV.

    I have thought of storing it using integers which I would assume uses less space than storing strings for everything that could easily be expressed as an integer

    True.

    other upside I see of using integers is that if I wanted to rename an achievement or rank I could easily change it without even having to touch the database.

    This is a key benefit of integers in my opinion. However, it also requires you to make sure the associated values of the enum don't change. If you screw that up, you'll almost certainly wreak havoc, which is a huge disadvantage.

    A benefit I see for using strings is that the data requires less processing before it is used

    If you're actually using an enum data type, it's probably some kind of integer internally, so the integer should require less processing. Either way, that overhead should be negligible.

    Is there an strong reason to use either integers or strings?

    I'm repeating a lot of what's been said, but maybe that helps other readers. Summing up:

    • Mixing up the enum value map wreaks havoc. Imagine your Declined states are suddenly interpreted as Accepted, because Declined had the value '2' and now it's Accepted because you reordered the enum and forgot to assign values manually... (shudders)
    • Strings are more expressive
    • Integers take less space. Disk space doesn't matter, usually, but index space will eat RAM which is expensive.
    • Integer updates don't resize the object. Strings, if their lengths vary greatly, might require a reallocation. String padding and padding factor should alleviate this, though.
    • Integers can be flags (not yet queryable (yet), unfortunately, see SERVER-3518)
    • Integers can be queried by $gt / $lt so you can efficiently implement complex $or queries, though that is a rather arcane requirement and there's nothing wrong with $or queries...

    0 讨论(0)
提交回复
热议问题