有没有办法将用shell查询语法表示的查询提交给mongo c#驱动程序
例如类似的东西
Coll.find { "myrecs","$query : { x : 3, y : "abc" }, $orderby : { x : 1 } } ");
以shell指南为例
最佳答案
没有您想要的完全相同的功能。
但你可以从 json 创建 BsonDocument 进行查询:
var jsonQuery = "{ x : 3, y : 'abc' }";
BsonDocument doc = MongoDB.Bson.Serialization
.BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
然后你可以从 BsonDocument 创建查询:
var query = new QueryComplete(doc); // or probably Query.Wrap(doc);
你可以对排序表达式做同样的事情:
var jsonOrder = "{ x : 1 }";
BsonDocument orderDoc = BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
var sortExpr = new SortByWrapper(orderDoc);
您也可以像这样为 MongoCollection 创建扩展方法:
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();
}
我没有测试上面的代码。如果需要,稍后会做。
更新:
刚刚测试了上面的代码,它工作正常!
你可以这样使用它:
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 }");
关于c# - 我可以使用 mongodb c# 驱动程序进行文本查询吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6120629/