Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

402
Views
MongoDB C# Delete filtered records excluding last N number of records

How can I delete filtered records from a collection excluding last N number of records.

Example: filter by Id and then keep last 10 records and delete all other with that Id.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can do that by first filtering the rows, then creating delete filter and finally apply the delete as follows. this sample has used MongoDb.Driver for .net.

 var listFilter = Builders<Entity>.Filter.Eq(s => s.SomeProp, X);
 SortDefinition<Entity> sortDefinition = Builders<Entity>.Sort.Ascending(a => a.SomeProp);
 List<Entity> itemsAfterSkip = await this.DbSet.Find(listFilter).Sort(sortDefinition).Skip(10).Limit(10).ToListAsync();
 FilterDefinition<Entity> deleteFilter = null;
 foreach (var item in itemsAfterSkip)
 {
       if (deleteFilter == null)
       {
          deleteFilter = MongoDB.Driver.Builders<Entity>.Filter.Eq(s => s.Id, item.Id);
       }
       else
       {
           deleteFilter = deleteFilter | MongoDB.Driver.Builders<Entity>.Filter.Eq(s => s.Id, item.Id);
       }
}          

await DbSet.DeleteManyAsync(deleteFilter);
over 4 years ago · Santiago Trujillo Report

0

here's my solution using MongoDB.Entities package:

using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TestApplication
{
    public class Person : Entity
    {
        public string Name { get; set; }
        public int NIC { get; set; }
    }

    public static class Program
    {
        private static async Task Main()
        {
            await DB.InitAsync("test");

            var people = new List<Person>();

            for (int i = 1; i <= 20; i++)
            {
                people.Add(new Person { Name = $"person {i}", NIC = i });
            }

            await people.SaveAsync();

            var idsToDelete = await DB.Queryable<Person>()
                .OrderByDescending(p => p.ID)
                .Skip(10)
                .Select(p => p.ID)
                .ToListAsync();

            await DB.DeleteAsync<Person>(idsToDelete);
        }
    }
}

disclaimer: i'm the author of the library.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!