Lee
Lee

Reputation: 768

How to Date.Month and Date.Day in MongoDb

Having difficulty querying Birtday(DateTime) from Customer

Query<Customer>.Where(a => a.Birthday.Month == startDate.Month && a.Birthday.Day == startDate.Day)

I am getting this message:

Unable to determine the serialization information for the expression: a.Birthday.Month.

[Update]

Model:

public class Customer
{
    public ObjectId Id { get; set; }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public DateTime Birthday { get; set; }
}

Upvotes: 2

Views: 1059

Answers (2)

idbentley
idbentley

Reputation: 4218

If you are able to change your schema, I'd recommend doing so, and replacing Birthday with an embedded document:

{
    _id: Object(),
    FirstName: string,
    ...
    Birthday: {
        date: ISODate(),
        year: int,
        month: int,
        day: int
    }
}

And precalculate the year, month and day in your application logic before your initial insertion of the document. This will allow the query you specify in your question.

Using $where as you have done in your solution is very inefficient for queries, and eating the cost at insertion time is probably worthwhile.

Upvotes: 0

Lee
Lee

Reputation: 768

Here is the solution that I came up.

var script = new BsonJavaScript("return ((this.Birthday.getMonth() == 0) && (this.Birthday.getDate() == 5))");

var mongoQuery = MongoDB.Driver.Builders.Query.Where(script);

var ret = GetCollection<Customer>().Find(mongoQuery);

Upvotes: 1

Related Questions