我可以使用mongodb c#驱动程序进行文本查询吗 [英] Can I do a text query with the mongodb c# driver

查看:112
本文介绍了我可以使用mongodb c#驱动程序进行文本查询吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将以shell查询语法表示的查询提交给mongo c#驱动程序

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

例如类似

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

以shell指南为例

推荐答案

您没有完全相同的功能.

There is no exact same functionality you want.

但是您可以从json创建BsonDocument进行查询:

But you can create BsonDocument from json for query:

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

然后,您可以从BsonDocument创建查询:

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

您还可以像这样为MongoCollection创建扩展方法:

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.

更新:

只需测试上面的代码,它就可以工作!

Just tested the code above, it's working!

您可以像这样使用它:

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

这篇关于我可以使用mongodb c#驱动程序进行文本查询吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆