简体   繁体   中英

How to find an entry in a Mongo Collection through C# driver by DateTime?

I keep a bunch of objects of the below structure in a Mongo collection. I try to resketch the most important points sort of pseudo-code like, hopefully no elementary functions are missing to understand my question:

public class O {
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public int c { get; set; }
    
    [BsonElement]
    [BsonDateTimeOptions(DateOnly = true)]
    public DateTime date { get; set; }
}

Through an ASP.NET Core controller class, comes in a request to find an object by date:

public class Contrl : ControllerBase {
    private readonly OService _oserv;

    [HttpGet]
    public ActionResult<O> GetByDate([FromQuery] int c, [FromQuery] DateTime date) {
        _oserv.GetByDate(c, date);
    }
}

The service then connects to the DB and submits the query (LINQ) and uses a helper method ( IsSameDate ) to check if the dates match:

public class OService {

    private readonly IMongoCollection<O> _repo;

    public List<O> GetByDate(int c, DateTime date) {
        O searchResult = _repo.Find<O>(o => IsSameDate(o.date, date).FirstOrDefault();
    }

    public bool IsSameDate(DateTime d1, DateTime d2) => 
        d1.Year == d2.Year && d1.Month == d2.Month && d1.Day == d2.Day;
}

I receive a HTTP 500 error and in the Error message it says:

System.ArgumentException: Unsupported filter: 
value(proj.Services.OService).IsSameDate({document}{date}, 20/02/2020 00:00:00).

So it looks like its going in the right direction but it doesn't use o.date in the helper method, instead it uses {document}{date} , what is that and how to do this correctly?

If you want to filter by Date Only then there is below way:

First you have to create two Date like below,

public List<O> GetByDate(int c, DateTime date) {
   var startDate = new DateTime(date.Year, date.Month, date.Day);
   var endDate = startDate.AddDays(1);

   var filter = Builders<O>.Filter.Gte(x => x.date, startDate)
                 & Builders<O>.Filter.Lt(x => x.date, endDate);

   //Note get your Collection before this line and then use it.

   O searchResult = await Collection.Find(filter).FirstOrDefaultAsync();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM