MongoDB GetCollection 方法是否将整个集合加载到 RAM 或引用中?C# [英] Does MongoDB GetCollection method load the entire collection into RAM or a reference? C#

查看:57
本文介绍了MongoDB GetCollection 方法是否将整个集合加载到 RAM 或引用中?C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储库类,用于处理 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<位置>("位置");}

然后我会做这样的事情:

_collection.Insert(locationObject)

在类的其他方法中.

我想知道考虑到内存有限,这样做是否可取?如果没有,是否有一种明智的方法可以直接持久保存到数据库而无需加载集合.

解决方案

GetCollection 不会加载集合,即使是 Find() 也不会.事实上,您必须在任何内容从数据库实际加载之前开始迭代MongoCursor,即使这样,它也不会加载整个集合,而只会加载批处理可配置大小.

如果你想真正加载整个集合,你可以在 MongoCursor 上调用 ToList(),例如,但当然这很少有意义.p>

I have a repository class that handles all database functions for MongoDB, this is the implementation of the constructor:

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");
}

I then do stuff like:

_collection.Insert(locationObject)

in other methods of the class.

I want to know if this is advisable considering limited memory? if not, is there an advisable way to persist directly to the DB without having to load the collection.

解决方案

GetCollection doesn't load the collection, not even a Find() will. In fact, you'll have to start iterating the MongoCursor before anything is actually loaded from the database, and even then, it won't load the entire collection but only batches of configurable size.

If you wanted to actually load the entire collection, you could call ToList() on the MongoCursor, for instance, but of course that rarely makes sense.

这篇关于MongoDB GetCollection 方法是否将整个集合加载到 RAM 或引用中?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆