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

发布于 2024-11-10 00:54:25 字数 188 浏览 4 评论 0原文

有没有办法将 shell 查询语法表示的查询提交给 mongo c# 驱动程序

例如,

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

从 shell 指南中获取示例

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","$query : { x : 3, y : "abc" }, $orderby : { x : 1 } } ");

To take an example from the shell guide

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

娇俏 2024-11-17 00:54:25

没有您想要的完全相同的功能。

但是您可以从 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 }");

There is no exact same functionality you want.

But you can create BsonDocument from json for query:

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

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

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.

Update:

Just tested the code above, it's working!

You can use it like this:

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 }");
花桑 2024-11-17 00:54:25

QueryComplete 类似乎已被弃用。使用 MongoDB.Driver.QueryDocument 代替。如下:

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

The QueryComplete class seems to have been deprecated. Use MongoDB.Driver.QueryDocument instead. As below:

BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ name : value }");
QueryDocument queryDoc = new QueryDocument(document);
MongoCursor toReturn = collection.Find(queryDoc);
傲影 2024-11-17 00:54:25

这是我编写的一个 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 条记录,其中值 >= 23 且值 <= 26,按降序

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

排列!

Here is a web service function I wrote which you can send in a filter query, limit, and skip for pagination and a sort query for any collection you want! It's generic and fast.

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

Assuming I had these records in my collection called "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" }]

I could make the web service call with the following parameters to return 100 records starting with the first page where value >= 23 and value <= 26, in descending order

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

Enjoy!

默嘫て 2024-11-17 00:54:25

以下是我用于从字符串和 .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>;
    }

使用这些例程,可以很容易地通过字符串或对象参数进行查询:

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 字符串中嵌入的引号(如果它们是手工编码的)要容易一些。

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

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<Question>(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<Question>(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.

鸠书 2024-11-17 00:54:25

使用 官方 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 })

Using the official C# driver, you'd do something like this:

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

The equivalent query from the shell would be:

col.find({ x: 3, y: "abc" }).sort({ x: 1 })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文