I have data in mongodb something like so. There is a collection of cats. The cats are sorted into different categories and ranked 1 through 100. One cat might be located in 2 or more categories. There are 1000s of categories.
COLLECTION: "cats"
KEYS:
rank.category1 = 1; // ranked 1st in category #1
rank.category2 = 13; // ranked 13th in category #2
rank.category425 = 50; // ranked 50th in category #425
QUESTION: If I want to do a find() to return all "cats" that have a "rank" in "category2" where $exists => "rank.category2" what is the proper way to index this? Can I just put a simple ascending index on "rank" collection or do I need an index on all 1000+ category* keys? Is there a better way to store this information or an easier way to index it?
To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.
Indexes store references to fields in either ascending ( 1 ) or descending ( -1 ) sort order. For single-field indexes, the sort order of keys doesn't matter because MongoDB can traverse the index in either direction.
How about ...
rank.categories = [1, 2, 425];
rank.category = {
1 : 1,
2 : 13,
425 : 50
}
You can index db.collection.ensureIndex({"categories":1})
. Now you can search through categories and get ranking of each when you find one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With