Search code examples
c#.netmongodbmongodb-.net-driver

I need a C# function to return the last N items entered in a MongoDB database


I need to implement a function that does exactly this:

db.foo.find().sort({date:1}).limit(50);

but I have no idea how to do it in C#, using the MongoDB.Driver. I tried to read the documentation for hours, but it's so messy and confusing and I can't get anything to work.

The function should be as follows:

// Function to find last N entries
public string[] lastNEntries(int N)
{
    // Get the last N entries of the "text" key as a string array
    return list;
}

Solution

  • You may try something like:

            var client = new MongoClient();
            var db = client.GetDatabase("dataBase");
            var msgs = db.GetCollection<Entity>("collection");
    
            //if you need a filter too
            var filter = Builders<Entity>.Filter.Gt("date",new DateTime(2001,1,1));
            var sort = Builders<Entity>.Sort.Descending("date");
            List<Entity> result = await msgs.Find(filter).Sort(sort).Limit(50).ToListAsync();
    

    (entity is just some kind of class with the appropriate structure)