Harry
Harry

Reputation: 54949

MongoDB overlapping indexes, waste of space or not?

I'm doing queries like this:

.find({name: "bob", gender: "male"})
.find({name: "alice"})

I created 2 indexes, one with {"name": 1}, and the other {"name": 1, "gender": 1}

Does creating 2 indexes make sense here? Is it a waste of space to do so? Can I for example, get rid of the name index?

Upvotes: 2

Views: 537

Answers (1)

Despagito
Despagito

Reputation: 386

yes, it's a waste of memory, all you need is a compound index of 'name' and 'gender'.

db.table.createIndex( { "name": 1, "gender": 1 } )

This allows you both options. You can query on just name, and you also can query on category combined with item. A single compound index on multiple fields can support all the queries that search a “prefix” subset of those fields.

ref: https://docs.mongodb.com/manual/tutorial/create-indexes-to-support-queries/#create-compound-indexes-to-support-several-different-queries

Upvotes: 1

Related Questions