我可以使用mongodb c#驱动程序进行文本查询
有没有办法将shell查询语法中表达的查询提交给mongo c#驱动程序
比如说像
Coll.find { "myrecs","$query : { x : 3, y : "abc" }, $orderby : { x : 1 } } ");
以shell指南为例
您没有完全相同的function。
但您可以从json创建BsonDocument以进行查询:
var jsonQuery = "{ x : 3, y : 'abc' }"; BsonDocument doc = MongoDB.Bson.Serialization .BsonSerializer.Deserialize(jsonQuery);
之后,您可以从BsonDocument创建查询:
var query = new QueryComplete(doc); // or probably Query.Wrap(doc);
您可以对排序表达式执行相同的操作:
var jsonOrder = "{ x : 1 }"; BsonDocument orderDoc = BsonSerializer.Deserialize(jsonQuery); var sortExpr = new SortByWrapper(orderDoc);
你也可以为MongoCollection创建扩展方法,如下所示:
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(); }
我没有测试上面的代码。 如果需要,会在以后做。
更新:
刚刚测试了上面的代码,它正在运行!
你可以像这样使用它:
var server = MongoServer.Create("mongodb://localhost:27020"); var collection= server.GetDatabase("examples").GetCollection("SO"); var items = collection.GetItems("{ x : 3, y : 'abc' }", "{ x : 1 }");
QueryComplete类似乎已被弃用。 请改用MongoDB.Driver.QueryDocument
。 如下:
BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize("{ name : value }"); QueryDocument queryDoc = new QueryDocument(document); MongoCursor toReturn = collection.Find(queryDoc);
这是我写的一个Web服务函数,您可以通过筛选查询,限制和跳过分页以及您想要的任何集合的排序查询! 它通用且快速。
/// /// This method returns data from a collection specified by data type /// /// /// filter is a json specified filter. one or more separated by commas. example: { "value":"23" } example: { "enabled":true, "startdate":"2015-10-10"} /// limit and skip are for pagination, limit is the number of results per page /// skip is is the page size * page. so limit of 100 should use skip 0,100,200,300,400, etc. which represent page 1,2,3,4,5, etc /// specify which fields to sort and direction example: { "value":1 } for ascending, {"value:-1} for descending /// [WebMethod] public string GetData(string dataType, string filter, int limit, int skip, string sort) { //example: limit of 100 and skip of 0 returns the first 100 records //get bsondocument from a collection dynamically identified by datatype try { MongoCollection col = MongoDb.GetConnection("qis").GetCollection (dataType); if (col == null) { return "Error: Collection Not Found"; } MongoCursor cursor = null; SortByWrapper sortExpr = null; //calc sort order try { BsonDocument orderDoc = BsonSerializer.Deserialize (sort); sortExpr = new SortByWrapper(orderDoc); } catch { } //create a query from the filter if one is specified try { if (filter != "") { //sample filter: "{tags:'dog'},{enabled:true}" BsonDocument query = BsonSerializer.Deserialize (filter); QueryDocument queryDoc = new QueryDocument(query); cursor = col.Find(queryDoc).SetSkip(skip).SetLimit(limit); if (sortExpr != null) { cursor.SetSortOrder(sortExpr); } return cursor.ToJson(); } } catch{} //if no filter specified or the filter failed just return all cursor = col.FindAll().SetSkip(skip).SetLimit(limit); if (sortExpr != null) { cursor.SetSortOrder(sortExpr); } return cursor.ToJson(); } catch(Exception ex) { return "Exception: " + ex.Message; } }
假设我的集合中有这些记录名为“mytest2”:
[{ "_id" : ObjectId("54ff7b1e5cc61604f0bc3016"), "timestamp" : "2015-01-10 10:10:10", "value" : "23" }, { "_id" : ObjectId("54ff7b415cc61604f0bc3017"), "timestamp" : "2015-01-10 10:10:11", "value" : "24" }, { "_id" : ObjectId("54ff7b485cc61604f0bc3018"), "timestamp" : "2015-01-10 10:10:12", "value" : "25" }, { "_id" : ObjectId("54ff7b4f5cc61604f0bc3019"), "timestamp" : "2015-01-10 10:10:13", "value" : "26" }]
我可以使用以下参数进行Web服务调用,以第一页开始返回100条记录,其中值> = 23,值<= 26,按降序排列
dataType: mytest2 filter: { value: {$gte: 23}, value: {$lte: 26} } limit: 100 skip: 0 sort: { "value": -1 }
请享用!
以下是我用于从字符串和.NET对象转换为BSON查询的一些例程(这是业务对象包装器的一部分,因此有几个引用该类):
public QueryDocument GetQueryFromString(string jsonQuery) { return new QueryDocument(BsonSerializer.Deserialize(jsonQuery)); } public IEnumerable QueryFromString (string jsonQuery, string collectionName = null) { if (string.IsNullOrEmpty(collectionName)) collectionName = this.CollectionName; var query = GetQueryFromString(jsonQuery); var items = Database.GetCollection (collectionName).Find(query); return items as IEnumerable ; } public IEnumerable QueryFromObject (object queryObject, string collectionName = null) { if (string.IsNullOrEmpty(collectionName)) collectionName = this.CollectionName; var query = new QueryDocument(queryObject.ToBsonDocument()); var items = Database.GetCollection (collectionName).Find(query); return items as IEnumerable ; }
使用这些通过字符串或对象parms查询非常容易:
var questionBus = new busQuestion(); var json = "{ QuestionText: /elimination/, GroupName: \"Elimination\" }"; var questions = questionBus.QueryFromString(json); foreach(var question in questions) { ... }
或使用对象语法:
var questionBus = new busQuestion(); var query = new {QuestionText = new BsonRegularExpression("/elimination/"), GroupName = "Elimination"}; var questions = questionBus.QueryFromObject(query); foreach(var question in questions) { ... }
我喜欢对象语法只是因为在C#代码中写出比在JSON字符串中处理嵌入式引号更容易,如果它们是手动编码的。
使用官方C#驱动程序 ,你会做这样的事情:
var server = MongoServer.Create("mongodb://localhost:27017"); var db = server.GetDatabase("mydb"); var col = db.GetCollection("col"); var query = Query.And(Query.EQ("x", 3), Query.EQ("y", "abc")); var resultsCursor = col.Find(query).SetSortOrder("x"); var results = resultsCursor.ToList();
来自shell的等效查询将是:
col.find({ x: 3, y: "abc" }).sort({ x: 1 })