[英]MongoDB C# Iteration as enumerator
I have a large collection of items with MongoDB (> 10m). 我使用MongoDB收集了大量项目(> 10m)。
The code is in C# / .NET. 该代码在C#/ .NET中。
On occasion, I need to iterate through all the documents to prune data, do some other maintenance, etc. also, in some cases, I need to be able to iterate through all documents but only get the Id of each document. 有时,我需要遍历所有文档以修剪数据,进行其他一些维护等。在某些情况下,我需要能够遍历所有文档,但仅获取每个文档的ID。
I want the documents to be presents as an IEnumerable for consumption by code which is used to process lists, etc. 我希望这些文档以IEnumerable的形式提供,以供用于处理列表等的代码使用。
I did the following: 我做了以下事情:
private static IAsyncCursor<MongoAlbum> GetCursor(Parameters...)
{
var F = MakeFilter(Parameters...);
var Cursor = Mongo.Driver.FindAsync(F).Result;
return Cursor;
}
internal static IEnumerable<string> IterateThroughAlbumIds(Parameters...)
{
using (var Cursor = GetCursor(Parameters...))
{
while (Cursor.MoveNextAsync().Result)
{
var Batch = Cursor.Current;
foreach (var Document in Batch) yield return Document._id;
}
}
}
internal static IEnumerable<MongoAlbum> IterateThroughAlbums(Parameters...)
{
using (var Cursor = GetCursor(Parameters...))
{
while (Cursor.MoveNextAsync().Result)
{
var Batch = Cursor.Current;
foreach (var Document in Batch) yield return Document;
}
}
}
Now I would like to know two things: 现在我想知道两件事:
You use ToEnumerable extension method for that and to get only the ID you need to use a projection. 为此,请使用ToEnumerable扩展方法,并仅获取使用投影所需的ID。
The following code should work 下面的代码应该工作
public class MongoAlbum
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Property { get; set; }
}
IMongoClient client;
IMongoDatabase database;
IMongoCollection<MongoAlbum> collection;
client = new MongoClient("connection string");
database = client.GetDatabase("DB name");
collection = database.GetCollection<MongoAlbum>("collection name");
IEnumerable<string> albums = collection.Find(x => x.Id == "1")
.Project(x => x.Id)
.ToEnumerable<string>();
In this case it will be a List of strings since you will only get Ids results and in my MongoAlbum POCO i used a string. 在这种情况下,它将是一个字符串列表,因为您只会得到Ids结果,并且在我的MongoAlbum POCO中我使用了一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.