pm100 pm100 - 1 year ago 86
C# Question

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

Answer Source

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

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);

   return cursor.ToList();

I am not tested above code. Will do it later if need.


Just tested above code, 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 }");