2011-05-25 49 views

回答

31

有你想不完全相同的功能。

但是你可以從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 }"); 
+0

這很接近。它仍然要求我解析用戶輸入的內容,並將其分解爲單獨的條款。 – pm100 2011-05-25 15:35:23

+0

SortBy.Wrap不會爲我編譯最新的git驅動程序。沒有這樣的方法 – pm100 2011-05-25 15:59:27

+0

新的SortByWrapper(orderDoc) – pm100 2011-05-26 00:19:52

0

使用official C# driver一個例子,你會做這樣的事情:

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

從外殼的等效查詢是:

col.find({ x: 3, y: "abc" }).sort({ x: 1 }) 
+3

Thx克里斯,但這不是我正在尋找。我知道如何創建這樣的查詢。但那不是我想要的。我希望用戶能夠將查詢字符串輸入到我的應用程序中,然後執行它 – pm100 2011-05-25 15:47:44

+0

嗯,好的,我沒有正確地閱讀該問題:) – 2011-05-25 22:50:18

14

的QueryComplete類似乎已經過時了。使用MongoDB.Driver.QueryDocument代替。如下圖所示:

BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ name : value }"); 
QueryDocument queryDoc = new QueryDocument(document); 
MongoCursor toReturn = collection.Find(queryDoc); 
+1

請詳細解答這個問題。 – Stunner 2013-06-06 22:32:49

+0

感謝您提供最新的相關解決方案。 – 2014-12-17 04:10:58

4

這裏有幾個程序我用從字符串轉換以及從.NET對象BSON查詢(這是業務對象包裝內,以便一對夫婦裁判的該類的一部分):

public QueryDocument GetQueryFromString(string jsonQuery) 
    { 
     return new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(jsonQuery)); 
    } 

    public IEnumerable<T> QueryFromString<T>(string jsonQuery, string collectionName = null) 
    { 
     if (string.IsNullOrEmpty(collectionName)) 
      collectionName = this.CollectionName; 

     var query = GetQueryFromString(jsonQuery);    
     var items = Database.GetCollection<T>(collectionName).Find(query); 

     return items as IEnumerable<T>; 
    } 


    public IEnumerable<T> QueryFromObject<T>(object queryObject, string collectionName = null) 
    { 
     if (string.IsNullOrEmpty(collectionName)) 
      collectionName = this.CollectionName; 

     var query = new QueryDocument(queryObject.ToBsonDocument()); 
     var items = Database.GetCollection<T>(collectionName).Find(query); 

     return items as IEnumerable<T>; 
    } 

使用這些它很容易通過字符串或對象PARMS查詢:

var questionBus = new busQuestion();   
var json = "{ QuestionText: /elimination/, GroupName: \"Elimination\" }"; 
var questions = questionBus.QueryFromString<Question>(json); 

foreach(var question in questions) { ... } 

或使用對象語法:

var questionBus = new busQuestion();    
var query = new {QuestionText = new BsonRegularExpression("/elimination/"), 
       GroupName = "Elimination"}; 
var questions = questionBus.QueryFromObject<Question>(query); 

foreach(var question in questions) { ... } 

我喜歡的對象語法,只是因爲它是一個容易一點在C#代碼寫出來比在JSON字符串嵌入引號處理,如果他們硬編碼的。

4

這是一個Web服務功能我寫的,你可以在過濾器中查詢,限制發送,並跳過分頁和任何你想要的集合排序查詢!它通用且快速。

/// <summary> 
    /// This method returns data from a collection specified by data type 
    /// </summary> 
    /// <param name="dataType"></param> 
    /// <param name="filter">filter is a json specified filter. one or more separated by commas. example: { "value":"23" } example: { "enabled":true, "startdate":"2015-10-10"}</param> 
    /// <param name="limit">limit and skip are for pagination, limit is the number of results per page</param> 
    /// <param name="skip">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</param> 
    /// <param name="sort">specify which fields to sort and direction example: { "value":1 } for ascending, {"value:-1} for descending</param> 
    /// <returns></returns> 
    [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<BsonDocument> col = MongoDb.GetConnection("qis").GetCollection<BsonDocument>(dataType); 
      if (col == null) { 
       return "Error: Collection Not Found"; 
      } 

      MongoCursor cursor = null; 
      SortByWrapper sortExpr = null; 

      //calc sort order 
      try { 
       BsonDocument orderDoc = BsonSerializer.Deserialize<BsonDocument>(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<BsonDocument>(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條記錄開始的第一頁,其中value> = 23和值< = 26,按降序排列

dataType: mytest2 
filter: { value: {$gte: 23}, value: {$lte: 26} } 
limit: 100 
skip: 0 
sort: { "value": -1 } 

享受!

相關問題