使用JSON字符串C#蒙戈查询 [英] C# mongo queries with json strings

查看:182
本文介绍了使用JSON字符串C#蒙戈查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很基本的,我敢肯定,我只是忽略了一个类或方法的地方,但对我的生命,我找不到它。

This seems so basic that I'm sure I've just overlooked a class or a method somewhere, but for the life of me, I can't find it.

我有一个JSON字符串,像这样:

I've got a json string like so:

{ SendId: 4, "Events.Code" : { $all : [2], $nin : [3] } }

我可以在蒙戈运行此对壳找到()计数()和得到什么我要找的。
什么是处理这个在C#中最简单的方法?下面是我发现:

I can run this in the mongo shell against a find() or a count() and get what I'm looking for. What is the easiest way to deal with this in C#? Here's what I've found:


  • 我发现都希望该方法的 IMongoQuery ,这仅仅是一个标记接口

  • BsonDocument 有一个很好的解析方法,但它没有实现 IMongoQuery

  • QueryDocument BsonDocument ,它并落实 IMongoQuery ,但它不具有它自己的解析方法,我不能转换 QueryDocument BsonDocument

  • 聚合框架需要一个 BsonDocument [] ,但有时我只是想要一个简单的查找或计数操作

  • 其中一些查询大和总,我不希望建立他们行的时间与查询生成器类

  • The methods I'm finding are all wanting an IMongoQuery, which is just a marker interface
  • BsonDocument has a nice Parse method, but it doesn't implement IMongoQuery
  • QueryDocument inherits from BsonDocument, and it does implement IMongoQuery, but it does not have it's own Parse method, and I can't convert the QueryDocument to BsonDocument
  • The Aggregation framework takes a BsonDocument[], but sometimes I just want a simple Find or Count operation
  • Some of these queries are large and gross, and I don't want to build them a line a time with the Query builder class

如果使用JSON文件数据库的交易,我可以运行这个东西在外壳,是不是有一些方法,通过驱动程序来运行呢?

If the database deals with json documents, and I can run this stuff in the shell, isn't there some way to run it through the driver?

推荐答案

这是丑陋的,但你可以做到这一点在反序列化的字符串到 BsonDocument ,然后包裹在 QueryDocument

It's ugly, but you can do this by deserializing the string in to a BsonDocument and then wrapping in a QueryDocument

BsonDocument query = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ SendId: 4, 'Events.Code' : { $all : [2], $nin : [3] } }");
QueryDocument queryDoc = new QueryDocument(query);
var result = collection.FindAs<TypeOfResultExpected>(queryDoc); // or just use Find

如果这是你计划经常做的事情,你总是可以把它包装的方法,或者创建类似下面的 JSQueryDocument 类:

If it's something you plan on doing frequently, you could always wrap it in a method, or create a JSQueryDocument class like the following:

public class JSQueryDocument : QueryDocument
{
    public JSQueryDocument(string query) : base(MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query))
    {
        // Probably better to do this as a method rather than constructor as it
        // could be hard to debug queries that are not formatted correctly
    }
}

/// ...

var result = collection.Find(new JSQueryDocument("{ SendId: 4, 'Events.Code' : { $all : [2], $nin : [3] } }"));

这篇关于使用JSON字符串C#蒙戈查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆