Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do a MongoDB "starts with" query on an indexed subdocument field?

I'm trying to find documents where a field starts with a value.

Table scans are disabled using notablescan.

This works:

db.articles.find({"url" : { $regex : /^http/ }})

This doesn't:

db.articles.find({"source.homeUrl" : { $regex : /^http/ }})

I get the error:

error: { "$err" : "table scans not allowed:moreover.articles", "code" : 10111 }

There are indexes on both url and source.homeUrl:

{
    "v" : 1,
    "key" : {
        "url" : 1
    },
    "ns" : "mydb.articles",
    "name" : "url_1"
}

{
    "v" : 1,
    "key" : {
        "source.homeUrl" : 1
    },
    "ns" : "mydb.articles",
    "name" : "source.homeUrl_1",
    "background" : true
}

Are there any limitations with regex queries on subdocument indexes?

like image 546
Tom Robinson Avatar asked Oct 29 '14 13:10

Tom Robinson


People also ask

Can a query use multiple indexes MongoDB?

MongoDB can use the intersection of multiple indexes to fulfill queries. In general, each index intersection involves two indexes; however, MongoDB can employ multiple/nested index intersections to resolve a query.

How do I check if a field is indexed in MongoDB?

Finding indexes You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

How do I run a MongoDB query in Robo 3T?

Open Studio 3T and connect to your MongoDB database. Next, open the Import Wizard from the toolbar. Then, choose JSON as the import format. Click OK.

Does MongoDB index all fields?

MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.


1 Answers

When you disable table scans, it means that any query where a table scan "wins" in the query optimizer will fail to run. You haven't posted an explain but it's reasonable to assume that's what is happening here based on the error. Try hinting the index explicitly:

db.articles.find({"source.homeUrl" : { $regex : /^http/ }}).hint({"source.homeUrl" : 1})

That should eliminate the table scan as a possible choice and allow the query to return successfully.

like image 143
Adam Comerford Avatar answered Oct 09 '22 23:10

Adam Comerford