开发者

Implementing "$or" with C# driver (Samus) for MongoDB

开发者 https://www.devze.com 2023-01-27 08:08 出处:网络
Please, give me some s开发者_StackOverflow社区amples of queries in C# with \"$or\" logic. I am using C# driver,

Please, give me some s开发者_StackOverflow社区amples of queries in C# with "$or" logic. I am using C# driver, written by Samus (https://github.com/samus/mongodb-csharp)...


If you have a typed collection (the Person type in this example) you can do an OR using Linq:

var mongo = new Mongo("Server=localhost:27017");
mongo.Connect();

List<Person> people = mongo["dbName"].GetCollection<Person>("people").Linq().Where(x => x.Age == 21 || x.Age == 35).ToList();

mongo.Disconnect();

At the moment that won't use the "$or" operator (it will use JavaScript for the ||, see JavaScript Mode in this wiki page).

If you really want to use the "$or" operator you could build up a query document and pass an array of conditions to the "$or" operator:

var mongo = new Mongo("Server=localhost:27017");
mongo.Connect();

var query = new Document
{
    {"$or", new Document[] { new Document("Age", 21), new Document("Age", 35) } }
};
Document people = mongo["dbName"].GetCollection("people").Find(query);

mongo.Disconnect();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号