c# - 我可以使用 mongodb c# 驱动程序进行文本查询吗

标签 c# mongodb mongodb-.net-driver

有没有办法将用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/

相关文章:

node.js - 如何在不重复代码的情况下在实时数据库和生产数据库之间切换?

c# - 使用 MongoDB-CSharp 在 MongoDB 中正确抽象 OId

mongodb - 无法使用 MongoDBRef 枚举对象

mongodb - 在 mongodb 中使用随机键按嵌套文档值查找

c# - 双除以 1

c# - LINQ 是否允许简化此构造?

c# - Microsoft.Xrm.Tooling.Connector 高内存分配

mongodb - MongoDB如何对每组内max对应的文档进行分组和选取?

c# - 从C#mongodb驱动程序执行mongodb shell查询(最新)

c# - Image数据类型转Base64,Base64转Image数据类型