使用 .net 核心并 mongodb 了解性能

Working with .net core and mongodb understanding the performance

第一次有.net core,MongoDB平时用Entity FrameworkORM。 我使用 .net core 3 和 MongoDB 驱动程序 2.11 来处理数据库。

这是存储库服务的示例:

public class Repository<T> : IRepository<T> where T : IDocument
{
    private readonly IMongoCollection<T> _collection;

    public Repository(IDatabaseSettings settings)
    {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);
            _collection = database.GetCollection<T>(GetCollectionName(typeof(T)));
    }

    Task<T> FindOneAsync(Expression<Func<T, bool>> filterExpression){}
    Task<T> FindByIdAsync(string id){}
    Task InsertOneAsync(T document) {}
    Task InsertManyAsync(ICollection<T> documents){}
    Task ReplaceOneAsync(T document) {}
    Task DeleteOneAsync(Expression<Func<T, bool>> filterExpression){}
    Task DeleteByIdAsync(string id) {}
    Task DeleteManyAsync(Expression<Func<T, bool>> filterExpression){}
    
}

如您所见,这是存储库的标准定义 class。

我的问题是,当存储库与特定集合一起使用时,是否所有集合都加载到本地内存?

例如,如果我想在集合中查找特定文档, 然后在构造函数中使用 GetCollection 从数据库中获取集合,然后 运行 在本地集合中的所有文档上?

或者它是否生成一个查询并在数据库中执行它类似于 Entity Framework ORM?

My question is when the repository works with a specific collection does all collection is loaded to local memory?

没有

它只需要一个集合的“句柄”。它不会获取任何文档。

For example, if I want to find a specific document in the collection, then GetCollection in constructor fetching collection from database and running on all documents in the collection locally?

都没有。

您需要使用 FindOneFindById那些 将发出查询以获取文档(一个用于此目的)

顺便说一句,您可能还需要一个 Find(这样可以获得不止一个文档)

Or does it generate a query and execute it in a database similarly to Entity Framework ORM?

GetCollection 不生成查询以获取任何内容


好像有点“权威”,你可以打开一个mongoshell玩一下:

// just set up some data to collection dummy
> db.dummy.insert([{a:2},{a:1}])
// look for any document having field 'a' with value 1.
// only one doc returned, fair enough
> db.dummy.find({ a: 1 })
{ "_id" : ObjectId("60334ea3623e06e621f86a0b"), "a" : 1 }

// this is equivalent to
> db.getCollection('dummy').find({ a: 1 })
// without the find() you just get information on the collection, NO documents fetched
// imagine collection as an object, on which you can issue queries (find, findOne, remove, ...)
// but not necessarily query to touch documents: e.g ensureIndex, help, ...
// (just type <<tab>> to see available commands)
> db.getCollection('dummy')
dummy.dummy

附带说明,getCollection 允许使用有点特殊的命名来定位集合名称,例如

db._dummy.insert({ a: 1 }) // fails because of '_' char
uncaught exception: TypeError: db._dummy is undefined :
db.getCollection('_dummy').insert({ a: 1 })
WriteResult({ "nInserted" : 1 })