Can I do a text query with the mongodb c# driver

前端 未结 5 2067
萌比男神i
萌比男神i 2020-12-12 17:52

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

For example Something like

Coll.find { \"myrecs\"         


        
5条回答
  •  隐瞒了意图╮
    2020-12-12 18:06

    Here are a few routines I use for converting from string and from .NET objects to BSON queries (this is part of business object wrapper so a couple of refs to that class):

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

    Using these it's pretty easy to query via string or object parms:

    var questionBus = new busQuestion();           
    var json = "{ QuestionText: /elimination/, GroupName: \"Elimination\" }";
    var questions = questionBus.QueryFromString(json);
    
    foreach(var question in questions) { ... }
    

    or using object syntax:

    var questionBus = new busQuestion();            
    var query = new {QuestionText = new BsonRegularExpression("/elimination/"), 
                     GroupName = "Elimination"};
    var questions = questionBus.QueryFromObject(query);
    
    foreach(var question in questions) { ... }
    

    I like the object syntax simply because it's a bit easier to write out in C# code than dealing with embedded quotes in JSON strings if they are handcoded.

提交回复
热议问题