programing

mongodbc# 드라이버로 텍스트 쿼리를 수행할 수 있습니까?

css3 2023. 6. 24. 09:26

mongodbc# 드라이버로 텍스트 쿼리를 수행할 수 있습니까?

셸 쿼리 구문으로 표현된 쿼리를 mongoc# 드라이버에 제출할 수 있는 방법이 있습니까?

예를 들어, 비슷한 것.

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

셸 가이드의 예를 보려면 다음과 같이 하십시오.

원하는 것과 정확히 동일한 기능은 없습니다.

그러나 쿼리를 위해 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 }");

쿼리 완료 클래스가 더 이상 사용되지 않는 것 같습니다.사용하다MongoDB.Driver.QueryDocument대신.아래와 같이:

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

여기 제가 작성한 웹 서비스 기능이 있습니다. 페이지화를 위해 필터 쿼리, 제한 및 건너뛰기를 보낼 수 있고 원하는 컬렉션에 대한 정렬 쿼리를 보낼 수 있습니다.일반적이고 빠릅니다.

    /// <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" }]

다음 매개 변수로 웹 서비스를 호출하여 값 > = 23 및 값 < = 26의 첫 페이지에서 시작하는 100개의 레코드를 내림차순으로 반환할 수 있습니다.

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<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) { ... }

JSON 문자열에 포함된 인용문을 수동으로 코딩하는 것보다 C# 코드로 쓰는 것이 조금 더 쉽기 때문에 객체 구문을 좋아합니다.

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

셸의 동등한 쿼리는 다음과 같습니다.

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

언급URL : https://stackoverflow.com/questions/6120629/can-i-do-a-text-query-with-the-mongodb-c-sharp-driver