Domanda

Suppose I have a data structure in the form of [String, int], I would like to be able to do lookups in O(1) time. In traditional SQL databases, I can simply create a look-up table.

How can I translate the same to mongodb such that I can use the String element as the key and int as the value?

È stato utile?

Soluzione

In MongoDB, your documents would need to be structured like this:

{
   key: "the key name"
   value: 100
}

Then, you'd create an index:

db.myLookupTable.ensureIndex({key : 1})

It's not going to be O(1) time though as it's not a Hash lookup. As explained here, indexes, by default, in MongoDB are B-tree based so that other types of operations are possible (like sorting which you could not get from a Hash-based index). B-trees are worst case O(log n).

You could also enable the Hashed indexes for an index in MongoDB:

db.myLookupTable.ensureIndex({key: "hashed" })

That limits the types of queries you can do on the index though. For example, range queries are not possible.

Altri suggerimenti

MongoDB allows you to create an index on fields in a collection; however, these are B-tree indexes and would result in lookups that are O(log n).

If you need O(1) lookups, then I would suggest using Redis.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top