Home > Net >  How to get a MongoDB BsonDocument from a collection based on last timestamp and some other filters u
How to get a MongoDB BsonDocument from a collection based on last timestamp and some other filters u

Time:11-30

For a building security system I want to get the last swiped card time for a particular student based on their id serial number. I am using this code

var _collection = database.GetCollection<BsonDocument>("entrycard_swipetimes");
var filter = Builders<BsonDocument>.Filter.Eq("studentid", "stu-1234") & Builders<BsonDocument>.Filter.Eq("Carddetails.LastSwipeTimestamp", "2021-11-25T10:50:00.5230694Z");
var doc = _collection.Find(filter).FirstOrDefault();

This is a snippet of the json document

{
  "studentid"; "stu-1234",
  "Carddetails": 
   { 
      "LastSwipeTimestamp": "2021-11-25T10:50:00.5230694Z"
    }
}

The code above works and I get a record, but I need to know the exact time string in advance. How can get only the last time a particular student swiped their card? How do I get the last timestamp of all the students in the system and have it paged by say 20 students at a time for the last 30 days?

CodePudding user response:

To get the last time a particular student (studentId) swiped their card:

var filter = Builders<BsonDocument>.Filter.Eq("studentid", studentId);
var doc = collection
    .Find(filter)
    .SortByDescending(bson => bson["Carddetails.LastSwipeTimestamp"])
    .FirstOrDefault();

To get the last timestamp of all the students in the system and have it paged by pageSize students at a time for the last lastDaysCount days:

var doc = collection
    .Aggregate()
    .Group(new BsonDocument
    {
        { "_id", "$studentid" },
        {
            "LastSwipeTimestamp", new BsonDocument
            {
                { "$max", "$Carddetails.LastSwipeTimestamp" }
            }
        },
    })
    .Match(bson => bson["LastSwipeTimestamp"] > DateTime.Now.AddDays(-lastDaysCount))
    .Skip((page - 1) * pageSize)
    .Limit(pageSize)
    .ToList();

But for this to work, you should store your dates as Date type.

CodePudding user response:

Modify Filter and add a sort thusly:

var filter = Builders<BsonDocument>.Filter.Eq("studentid", "stu-1234");

var doc = _collection.Find(filter).Sort("{Carddetails.LastSwipeTimestamp:-1}").FirstOrDefault();

Highly recommend that you change Carddetails.LastSwipeTimestamp to be a real datetime type instead of an ISO8601 string.

  • Related