FindAll in MongoDB .NET Driver 2.0

[亡魂溺海] 提交于 2019-12-05 16:23:31

问题


I want to query my MongoDB collection without any filter with MongoDB .NET Driver 2.0 but I didn't find a way. I have the following workaround but it looks weird :D

var filter = Builders<FooBar>.Filter.Exists(x => x.Id);
var fooBars = await _fooBarCollection.Find(filter)
    .Skip(0)
    .Limit(100)
    .ToListAsync();

Is there a way to issue queries without a filter in MongoDB .NET Driver 2.0?


回答1:


You can't use Find without a filter.

You can however use a filter that passes everything:

var findFluent = await _fooBarCollection.Find(_ => true);

Or you can use an empty document which is equivalent:

var findFluent = await _fooBarCollection.Find(new BsonDocument());

They have also added an empty filter but it will only be available in newer versions of the driver:

var findFluent = await _fooBarCollection.Find(Builders<FooBar>.Filter.Empty);



回答2:


FindAll() is the part of MongoDB 1x series driver. to get the same functionality in 2x series driver use find() with empty BSON Document.

var list = await collection.Find(new BsonDocument()).ToListAsync();
foreach (var dox in list)
{
    Console.WriteLine(dox);
}

Reference




回答3:


It works for me

public class TestProductContext
{
    MongoClient _client;
    IMongoDatabase _db;

    public TestProductContext()
    {
        _client = new MongoClient("mongodb://localhost:27017");
        _db = _client.GetDatabase("EmployeeDB");

    }

    public IMongoCollection<Product> Products => _db.GetCollection<Product>("Products");
}

public class DataAccess
{
    private TestProductContext _testProductContext;

    public DataAccess(TestProductContext testProductContext)
    {
        _testProductContext = testProductContext;
    }
    public List<Product> GetProducts()
    {
        List<Product> pto = new List<Product>();
        var cursor = _testProductContext.Products.Find(new BsonDocument()).ToCursor();
        foreach (var document in cursor.ToEnumerable())
        {
            pto.Add(document);
        }
    }
}


来源:https://stackoverflow.com/questions/30829282/findall-in-mongodb-net-driver-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!