Search code examples
c#.netmongodbmongodb-.net-driver

And operator in MongoDB to perform query with multi-filters using the official .NET driver


I am using MongoDB 3.2 and I want to make a query from C# using the official .NET driver (2.6)

Use Robomongo to perform the search, and the correct query is:

db.getCollection('collection1').find({ $and: [ { type: "ws128" }, { tsend: { $gte: ISODate("2018-05-11T14:39:33.000Z"), $lt: ISODate("2018-05-11T14:39:40.000Z") } }  ] })

I want to find all the documents that have the key type = ws128 and that the variable tsend is between the two dates that are shown in the query.

In C #, I have the filters defined as shown below but I do not know how to do the query:

DateTime datetimestart =  new DateTime(2018, 5, 11, 14, 39, 33);
DateTime datetimeend =  new DateTime(2018, 5, 11, 14, 39, 40);
var filter1 = Builders<BsonDocument>.Filter.Eq("type", "ws128");
var filter2 = Builders<BsonDocument>.Filter.Gte("tsend", datetimeend);
var filter3 = Builders<BsonDocument>.Filter.Lt("tsend", datetimestart);

With a single filter, the search performed without problems as shown below, but I do not know how to include the 3 filters.

var cursor = collection.Find(filter1).ToCursor();

Can someone guide me to continue? Thank you! regards,


Solution

  • You can simply do:

    collection.Find(filter1 & filter2 & filter3)
    

    or alternatively:

    collection.Find(Builders<BsonDocument>.Filter.And(filter1, filter2, filter3))