Diego
Diego

Reputation: 7562

MongoDB design - Same document with multiple keys

I'm completely new to MongoDB, and I'm confused on how to structure the data. What I need to do is storing a set of objects which can be retrieved by different keys. For example, I have the object "CustomerInfo" and it can be referenced by keys "Customer1", "Customer_1", "Cust.1", "Customer 1" and so on.

In an RDMBS I would create a separate table to store the aliases, and have a single row for the Customer Info data. Then I'd join them, using whatever alias I get from the Customer, and get to the data. It seems simple and straightforward, but, so far, I couldn't get past creating an empty database. It seems that my experience with RDBMS is more of a hindrance than an asset in this case, as I tend to "think relational" and it (obviously) doesn't apply to NoSQL databases.

Any suggestion is welcome, thanks in advance for all the answers.

Upvotes: 1

Views: 1629

Answers (1)

Remon van Vliet
Remon van Vliet

Reputation: 18625

If you cannot translate from an alias to an actual ID inside your app (which is always preferred) one option is to simply store an "aliases" array in your MongoDB documents and index on that :

Store documents like so :

db.customers {
    aliases : ["Customer1", "Customer_1", "Cust.1", "Customer 1"],
    ...other customer info data...
}

Add your index :

db.customers.ensureIndex({aliases:1})

And then simply query on any of them, all of these will return the document above :

db.customers.find({aliases: "Customer1"})
db.customers.find({aliases: "Customer_1"})
db.customers.find({aliases: "Cust.1"})
db.customers.find({aliases: "Customer 1"})

The index is optional but will dramatically improve performance.

Upvotes: 5

Related Questions