Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

397
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda