C# Driver: Example of iterating with an IAsyncCursor<> -- ListDatabasesAsync

3,169 views
Skip to first unread message

kof...@gmail.com

unread,
Apr 16, 2015, 1:49:06 PM4/16/15
to mongod...@googlegroups.com
I'd like to list all the databases and then print their names. Can anyone supply an example of how I iterate through the result of the ListDatabasesAsync()? I'm not sure what to do with the resulting cursor.

Robert Stam

unread,
Apr 16, 2015, 2:14:06 PM4/16/15
to mongod...@googlegroups.com
The easiest way to iterate over the values in a cursor is to use ToListAsync, assuming that you expect all the results to fit comfortably in memory at the same time.

Code to write the names of all the databases to the Console would look something like this:

    using (var cursor = await client.ListDatabasesAsync())
    {
        var databaseDocuments = await cursor.ToListAsync();
        foreach (var databaseDocument in databaseDocuments)
        {
            Console.WriteLine(databaseDocument["name"]);
        }
    }

On Thu, Apr 16, 2015 at 1:45 PM, <kof...@gmail.com> wrote:
I'd like to list all the databases and then print their names. Can anyone supply an example of how I iterate through the result of the ListDatabasesAsync()? I'm not sure what to do with the resulting cursor.

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at http://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/4dcd89a3-ecf6-4dde-a339-b8c15c6b7ee0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

kof...@gmail.com

unread,
Apr 16, 2015, 3:20:43 PM4/16/15
to mongod...@googlegroups.com
I ended up finding this solution:

            var cursor = await mongoClient.ListDatabasesAsync();
            await cursor.ForEachAsync(async (db) =>
            {
                string name = db.GetElement("name").Value.AsString;
                Console.WriteLine(name);
            });
        }

Thanks
Reply all
Reply to author
Forward
0 new messages