0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I am currently storing them as a document using the incoming json string data like so var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(data); var document = new BsonDocument().AddRange(bsonDoc); _collection.InsertOneAsync(document); How do I store the date in the json string data as Date type?
Check out stackoverflow.com/questions/2188585/… After you create document, navigate through the document (a Dictionary type) to where LastSwipeTimestamp is and replace it with the parsed datetime version before calling InsertOneAsync.
NOTE: MongoDB will only store milliseconds, not microseconds, so a successful parse of 2021-11-25T10:50:00.5230694Z will end up in MongoDB as ISODate(2021-11-25T10:50:00.523Z)
Thanks. Can you add to your answer how to get the last timestamp for every student ? that would make your answer complete.
? The Sort after the Find in my answer above coupled with FirstOrDefault will return the last (most recent) timestamp.
|
1

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.

1 Comment

I am currently storing them as a document using the incoming json string data like so var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(data); var document = new BsonDocument().AddRange(bsonDoc); _collection.InsertOneAsync(document); How do I store the date in the json string data as Date type?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.