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

How to fetch first 1000 documents that don't have certain field?


Say, I have collection People. How should I fetch first 1000 documents that doesn't have a field Phone? As I understand, I should use $exists however I cannot understand how to use it from .NET driver and there is next to no info on that topic on the internet. Any help will be appreciated. Thanks!


Solution

  • Assume your Model Class is Model and colelction name is "Model".

    var coll = db.GetCollection<Model>("Model");
    var ret = coll.Find(Builders<Model>.Filter.Exists(d => d.Phone, false))
                  .Limit(1000)
                  .ToList();
    

    With ToList you will get already loaded list, sometimes it's better to use ToEnumerable and have enumerable to iterate.