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,
What is a Filter? A filter modifies an incoming MongoDB query to return only a subset of the results matched by the query. Filters add additional query parameters and omit fields from query results before Atlas App Services runs the query.
$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .
Open Studio 3T and connect to your MongoDB database. Next, open the Import Wizard from the toolbar. Then, choose JSON as the import format. Click OK.
You can simply do:
collection.Find(filter1 & filter2 & filter3)
or alternatively:
collection.Find(Builders<BsonDocument>.Filter.And(filter1, filter2, filter3))
use a single &
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);
var andFilter = filter1 & filter2 & filter3;
var cursor = collection.Find(andFilter).ToCursor();
I would probably write that code a little differently. I find it easier to read and write:
DateTime datetimestart = new DateTime(2018, 5, 11, 14, 39, 33);
DateTime datetimeend = new DateTime(2018, 5, 11, 14, 39, 40);
var builder = Builders<BsonDocument>.Filter;
var filter1 = builder.Eq("type", "ws128");
var filter2 = builder.Gte("tsend", datetimeend);
var filter3 = builder.Lt("tsend", datetimestart);
var cursor = collection.Find(filter1 & filter2 & filter3).ToCursor();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With