LoveMeSomeCode
LoveMeSomeCode

Reputation: 3947

C# mongo queries with json strings

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.

I've got a json string like so:

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

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:

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?

Upvotes: 13

Views: 14930

Answers (2)

i3arnon
i3arnon

Reputation: 116636

To add to Shaun McCarthy's answer there's a slightly cleaner way to achieve the exact same goal using BsonDocument.Parse together with QueryDocument:

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

Upvotes: 13

Shaun McCarthy
Shaun McCarthy

Reputation: 1690

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

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] } }"));

Upvotes: 17

Related Questions