Thomas
Thomas

Reputation: 12107

MongoDB C# Iteration as enumerator

I have a large collection of items with MongoDB (> 10m).

The code is in 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.

I want the documents to be presents as an IEnumerable for consumption by code which is used to process lists, etc.

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:

Upvotes: 0

Views: 3809

Answers (1)

Eduardo
Eduardo

Reputation: 124

You use ToEnumerable extension method for that and to get only the ID you need to use a projection.

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.

Upvotes: 2

Related Questions