Search code examples
c#mongodbmongodb-.net-driver

Can I do a text query with the mongodb c# driver


Is there a way to submit a query that is expressed in the shell query syntax to the mongo c# driver

For example Something like

Coll.find { "myrecs","$query : { x : 3, y : "abc" }, $orderby : { x : 1 } } ");

To take an example from the shell guide


Solution

  • There is no exact same functionality you want.

    But you can create BsonDocument from json for query:

    var jsonQuery = "{ x : 3, y : 'abc' }";
    BsonDocument doc = MongoDB.Bson.Serialization
                       .BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
    

    And after that you can create query from BsonDocument:

    var query = new QueryComplete(doc); // or probably Query.Wrap(doc);
    

    The same you can do for the sort expression:

    var jsonOrder = "{ x : 1 }";
    BsonDocument orderDoc = BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
    
    var sortExpr = new SortByWrapper(orderDoc);
    

    Also you can create extension method for the MongoCollection like this:

    public static List<T> GetItems<T>(this MongoCollection collection, string queryString, string orderString) where T : class 
    {
        var queryDoc = BsonSerializer.Deserialize<BsonDocument>(queryString);
        var orderDoc = BsonSerializer.Deserialize<BsonDocument>(orderString);
    
        //as of version 1.8 you should use MongoDB.Driver.QueryDocument instead (thanks to @Erik Hunter)
        var query = new QueryComplete(queryDoc);
        var order = new SortByWrapper(orderDoc);
    
        var cursor = collection.FindAs<T>(query);
        cursor.SetSortOrder(order);
    
        return cursor.ToList();
    }
    

    I didn't test the code above. Will do it later if need.

    Update:

    Just tested the code above, it's working!

    You can use it like this:

    var server = MongoServer.Create("mongodb://localhost:27020");
    var collection= server.GetDatabase("examples").GetCollection("SO");
    
    var items = collection.GetItems<DocType>("{ x : 3, y : 'abc' }", "{ x : 1 }");