Click here to Skip to main content
15,886,052 members
Articles / Database Development / NoSQL

Beginners' guide to using MongoDB 4.0.2 and the official C# driver

Rate me:
Please Sign up or sign in to vote.
4.92/5 (43 votes)
16 Sep 2018CPOL13 min read 199.3K   3.4K   101  
Highlights the latest developments in both the Mongo open-source document database and the open-source official C# driver.
namespace TestMongo
{
    using System;
    using System.IO;
    using System.Linq;

    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    using MongoDB.Driver.GridFS;

    public partial class Program
    {
        #region Public Methods and Operators

        public static void DemoGridFS(MongoDatabase database)
        {
            var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var directoryName = Path.GetDirectoryName(assemblyPath);
            string fullyQualifiedUpLoadName = directoryName+@"\Images\mars.png";

            //The uploaded file name equals fullyQualifiedUpLoadName
            MongoGridFSFileInfo gridFsInfo = database.GridFS.Upload(fullyQualifiedUpLoadName);

            //Here the uploaded file is given the name 'mars.png'
            using (var fs = new FileStream(fullyQualifiedUpLoadName, FileMode.Open))
            {
                database.GridFS.Upload(fs, "mars.png");
            }
            // Add metadata to facilitate searching.
            var photoMetadata = new BsonDocument
            { { "Category", "Astronomy" }, { "SubGroup", "Planet" }, { "ImageWidth", 640 }, { "ImageHeight", 480 } };

            database.GridFS.SetMetadata(gridFsInfo, photoMetadata);

            //Build an index to search the metadata
            MongoCollection<BsonDocument> coll = database.GetCollection("fs.files");
            IndexKeysBuilder keys = IndexKeys.Ascending("metadata.Category", "metadata.SubGroup");

            //Add an optional name- useful for admin
            IndexOptionsBuilder options = IndexOptions.SetName("PhotoIndex");

            //This locks the database while the index is being built
            coll.EnsureIndex(keys, options);

            //Search using the PhotoIndex
            MongoCursor<MongoGridFSFileInfo> astronomyPics =
                database.GridFS.Find(Query.EQ("metadata.Category", "Astronomy"));

            //use a filename to download.
             string fullyQualifiedDownLoadName = directoryName + @"\Images\mars2.png"; ;
            database.GridFS.Download(fullyQualifiedDownLoadName, fullyQualifiedUpLoadName);

            MongoCursor<MongoGridFSFileInfo> filesInfo = database.GridFS.FindAll();
            if (filesInfo.Any())
            {
                Console.WriteLine("The following files have been uploaded.");
            }
            foreach (MongoGridFSFileInfo fileInfo in filesInfo)
            {
                Console.WriteLine(
                    "Name {0} size {1} uploaded on {2}",
                    fileInfo.Name,
                    fileInfo.Length,
                    fileInfo.UploadDate.ToShortDateString());
            }

            //  database.GridFS.Delete(fullyQualifiedUpLoadName);
            //  database.GridFS.Delete("mars.png");
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions