C # MongoDB query for timestamp less than current time

I am trying to return documents from a collection where id = 1 and the created date is less than the current time.

I tried this, but it does not work:

var collection = database.GetCollection("test"); var time = DateTime.Now; var query2 = new QueryDocument { { "id", 1}, {{"created_on", {"$lt",time}} }; 

What is wrong with this request?

+1
source share
1 answer

You need a built-in document for the $lt sub-object, but you forgot to create it:

 var query = new QueryDocument { { "id", 1 }, { "created_on", new BsonDocument { { "$lt", time } } } } 

Also consider using the Query constructor, which can simplify the task:

 var query = Query.And( Query.EQ("id", 1), Query.LT("created_on", time) ); 
+3
source

All Articles