Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

.net - 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:

  • 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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...