mongodbdictionaryindexingaggregation-frameworksubdocument

Can I index the keys of a object-type subdocument in MongoDB?


Is there any way where I can index my collection according to the keys of a subdocument of object type? And the keys are not uniform in all the documents, different documents have different keys, but there are some common keys. The keys of the subdocument are English words taken from the NLTK words corpus. The document structure is as follows:

{
    _id: 24752893,
    dictionary: {
        attain: {
            language: ....,
            count: ....,
        },
        book: {
            language: ....,
            count: ....,
        },
        obtain: {
            language: ....,
            count: ....,
        },
        ....
    }
},
{
    _id: 6786765789,
    dictionary: {
        book: {
            language: ....,
            count: ....,
        },
        carbon: {
            language: ....,
            count: ....,
        },
        garbage: {
            language: ....,
            count: ....,
        },
        ....
    }
},
........
{
    _id: 76675567,
    dictionary: {
        web: {
            language: ....,
            count: ....,
        },
        obtain: {
            language: ....,
            count: ....,
        },
        carbon: {
            language: ....,
            count: ....,
        },
        ....
    }
}

I want to index according to the keys of the object type dictionary field, i.e. the English words in order to speed up searching. I am using MongoDB version 4.4.


Solution

  • dictionary: [
        {
        attain: {
            language: ....,
            count: ....,
        },
        book: {
            language: ....,
            count: ....,
        },
        obtain: {
            language: ....,
            count: ....,
        }
    }
    ]
    

    --------------or use Attribute Pattern------------

    dictionary: [
        
        {
            k:'attain',
            language: ....,
            count: ....,
        },
        {
            k:'book',
            language: ....,
            count: ....,
        },
        {
            k:'obtain',
            language: ....,
            count: ....,
        }
    
    ]
    

    use $elemMatch to find the proper subset, your schema design is wrong Modify your schema like this and use multikey index. https://docs.mongodb.com/manual/core/index-multikey/

    db.collection.createIndex( { "dictionary.k": 1, "dictionary.language": 1,"dictionary.count":1 } )