这是我第一次拥有.net核心并且MongoDB通常使用Entity Framework ORM。我使用.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){}
}
如您所见,这是存储库类的标准定义。
我的问题是,当存储库与特定集合一起使用时,是否所有集合都已加载到本地内存?
例如,如果我想在集合中找到特定的文档,那么构造函数中的GetCollection从数据库中获取集合并在本地运行集合中的所有文档吗?
还是像Entity Framework ORM一样生成查询并在数据库中执行查询?
我的问题是,当存储库与特定集合一起使用时,是否所有集合都已加载到本地内存?
不。
它只需要一个“句柄”即可。它并没有获取任何文件。
例如,如果我想在集合中找到特定的文档,那么构造函数中的GetCollection从数据库中获取集合并在本地运行集合中的所有文档吗?
两者都不。
您将需要使用FindOne
或FindById
。这些将发出查询以获取文档(与此相关的一个)
顺便说一句,您可能还想要一个Find
(因此不只获得一个文档)
还是像Entity Framework ORM一样生成查询并在数据库中执行查询?
GetCollection
不会生成查询以获取任何内容
似乎有点“权威”,所以您可以打开mongo shell并玩一下:
// 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 })
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句