C# mongo queries with json strings

后端 未结 2 1214
陌清茗
陌清茗 2020-12-14 21:03

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:

2条回答
  •  北海茫月
    2020-12-14 21:47

    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("{ SendId: 4, 'Events.Code' : { $all : [2], $nin : [3] } }");
    QueryDocument queryDoc = new QueryDocument(query);
    var result = collection.FindAs(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(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] } }"));
    

提交回复
热议问题