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

前端 未结 5 2080
萌比男神i
萌比男神i 2020-12-12 17:52

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\"         


        
5条回答
  •  半阙折子戏
    2020-12-12 18:06

    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(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(jsonQuery);
    
    var sortExpr = new SortByWrapper(orderDoc);
    

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

    public static List GetItems(this MongoCollection collection, string queryString, string orderString) where T : class 
    {
        var queryDoc = BsonSerializer.Deserialize(queryString);
        var orderDoc = BsonSerializer.Deserialize(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(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("{ x : 3, y : 'abc' }", "{ x : 1 }");
    

提交回复
热议问题