我有一个repository类,它处理MongoDB的所有数据库函数,这是构造函数的实现:
public LocationRepository(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
connectionString = "mongodb://localhost:27017";
}
_client = new MongoClient(connectionString);
_server = _client.GetServer();
_database = _server.GetDatabase("locDb");
_collection = _database.GetCollection<Location>("Location");
}
然后我会做如下事情:
_collection.Insert(locationObject)
在类的其他方法中。
我想知道考虑到有限的记忆这是否明智?如果没有,是否有一种建议的方法可以直接持久化到数据库,而不必加载集合。
最佳答案
GetCollection
不会加载集合,甚至Find()
也不会加载。实际上,在实际从数据库加载任何内容之前,您必须开始迭代MongoCursor
,即使这样,它也不会加载整个集合,而只加载可配置大小的批。
例如,如果您想实际加载整个集合,您可以在ToList()
上调用MongoCursor
,但这几乎没有意义。