Search code examples
mongodbindexingmultikey

How to read multikey index values in MongoDB?


I would like to have autocomplete feature that suggests keywords from database. If I use MongoDB and multikey index, I kind of already have these keywords in database, but can I access them somehow?

If I have following object in collection:

{
    "title": "Some awesome title",
    "keywords": [
        "some",
        "awesome",
        "title"
    ]
}

And I have multikey index:

db.somecollection.ensureIndex({ "keywords" : 1 }) 

So index would contain following values:

"some"
"awesome"
"title"

If user enters "s" letter into autocomplete control, application should suggest "some" keyword. Can I search keywords from index or how should I do this?


Solution

  • You can choose to use aggregation framework:

    DEV:history:PRI > db.test.find()
    { "_id" : ObjectId("51c37c0c20d107378f9af3cc"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "title" ] }
    { "_id" : ObjectId("51c37de420d107378f9af3ce"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "something" ] }
    { "_id" : ObjectId("51c37f1920d107378f9af3cf"), "title" : "Some awesome title", "keywords" : [ "something", "awesome", "someone" ] }
    DEV:history:PRI > db.test.aggregate({$match : {keywords : /^som/}}, {$project:{keywords:1, _id : 0}}, {$unwind : "$keywords"}, {$match : {keywords : /^som/}}, {$group: {_id : '$keywords', count : {$sum : 1}}})
    {
        "result" : [
            {
                "_id" : "someone",
                "count" : 1
            },
            {
                "_id" : "something",
                "count" : 2
            },
            {
                "_id" : "some",
                "count" : 2
            }
        ],
        "ok" : 1
    }
    

    Note: Multi-key index are not covered and there are some JIRA issues already filed. So, despite of using indexes the queries are not covered (for multi-key indexes)

    We can optionally use the 'count' params to decide on the ordering in showing the auto-complete. If you don't require, remove from the query.