How mongodb sorts the documents when an object is used as an index?

36 Views Asked by At

If every document has an array of objects, let say :

hobbies:[
    {
        "title": "Swimming",
        "frequency": 4
    },
    {
        "title": "Playing",
        "frequency": 3
    }
]

and I use hobbies as an Index, then how all the documents in my db will be stored in an sorted manner? Which field will it consider to sort all the documents in index?

1

There are 1 best solutions below

0
On

You can create an index on hobbies field like this as a compound-index :

db.collection.createIndex( { "hobbies.title": 1, "hobbies.frequency": 1 } )

So as hobbies is an array then eventually if you get hobbies.title,hobbies.frequency it will also be an array, So as if MongoDB finds an array to be indexed then it would create multikey-index on that particular field (Basically in above scenario your document will be unwinded into two docs on title & frequency one for first object in array & another for second object in array in ascending order).