Journeyman
Journeyman

Reputation: 10281

MongoDB compound conditions in C#

How do I create compound condition when using the C# MongoDB driver?

This works:

mongoCollection = mdb.GetCollection("person");
BsonElement be1=new BsonElement("surname","Jones");
qryPattern = new QueryDocument(new BsonElement[] {be1});
foreach (MongoDB.Bson.BsonDocument doc in mongoCollection.FindAs<MongoDB.Bson.BsonDocument>(qryPattern))
{
    rc.Append(doc.ToJson());
    rc.Append("<br />");
}

But how do i adjust my BsonElement to support a compound condition, such as

BsonElement be1=new BsonElement("surname","[Jones,Smith]");

or even

BsonElement be1=new BsonElement("surname","Jones");
BsonElement be2=new BsonElement("surname","Smith");
qryPattern = new QueryDocument(new BsonElement[] {be1,be2});

Thanks very much

Upvotes: 2

Views: 1260

Answers (1)

Andrew Orsich
Andrew Orsich

Reputation: 53705

It's easy, you should use Query.In:

var names = new List<string>();
names.Add("Jones");
names.Add("Smith");
var query = Query.In("surname", BsonArray.Create(names));
collection.FindAs<BsonDocument>(query);

Upvotes: 1

Related Questions