Search code examples
mongodbmongodb-.net-driver

Is BsonJavaScript in MongoDB indexable?


I have the following code for retrieving messages in MongoDB which happen to have a bitwise flag "Status", which is why I am using the built in BsonJavaScript capability for filtering those records. Would the statement attempt to use an index for example on ToUserId or Status field even though it is using a JavaScript syntax for the query evaluation?

public long NewMessageCount
{
    get
    {
        var script = CreateScript("Status", MessageStatus.Unread);
        return MongoConnectionHandler.MongoCollection.Count(Query.Where(script));    
    }
}

public string ToUserId = "51e8dd21d84513129c644fa6";
public string CreateScript(string field, MessageStatus filter)
{
    return String.Format("this.ToUserId == '{0}' && (this.{1} & {2}) == {3}", ToUserId, field, (int)filter);
}

Solution

  • As per the documentation on $where as at MongoDB 2.4:

    $where evaluates JavaScript and cannot take advantage of indexes.
    

    I would encourage you to watch/upvote SERVER-3518 in the MongoDB issue tracker, which is a feature request for bitwise query operators.

    There isn't really a good workaround in the interim aside from copying the flags into boolean fields which do not require bitwise queries, or using an inefficient $where query.