AMIT SHELKE
AMIT SHELKE

Reputation: 533

MongoDb Query using C# for date time

I am working on MongoDb using C# drivers. I want query the mongoDb database to find out the row which has EventDate is greater than 13 months from todays date.

my MongoDb has structure something similar to below:

EventDate is of datatype : DateTime

{
   "_id" : ObjectId("525239e3e9374f1c3ce4123b"),
   "RowId" : 41133552,
   "EventDate" : ISODate("2013-08-19T00:00:28Z"),
   "Product" : "supporttool",
   "Language" : "en",
   "GUID" : "67cd73d4-36bc-4c9f-9a4c-144b38d4e928",
}

Please can anyone help me out to get the MongoCollection for data with event date older than 13 months.

Upvotes: 3

Views: 7092

Answers (2)

Bids
Bids

Reputation: 3

DateTime.UtcNow.AddMonths(-13) is a good example and works perfect.

Upvotes: 0

mnemosyn
mnemosyn

Reputation: 46331

There's more than one way to it, but this would be the one with LINQ extension method syntax:

MongoDatabase db = YourMongoDatabaseObject;
var cursor = db.GetCollection<YourClass>("yourClass").Find(
   Query<YourClass>.LT(p => p.EventDate, DateTime.UtcNow.AddMonths(-13));

This will return a cursor to all documents in the "yourClass" collection that have an an EventDate less than 13 months ago and will deserialize them as instances of YourClass.

Upvotes: 4

Related Questions