Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the proper way to ensureIndex index mongodb field on a multidimensional array?

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?

like image 340
Kyle Anderson Avatar asked Jan 18 '17 21:01

Kyle Anderson


People also ask

How do I index an array in MongoDB?

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.

Does index order matter MongoDB?

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.


1 Answers

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.

like image 141
kawadhiya21 Avatar answered Sep 28 '22 01:09

kawadhiya21