Monday, December 19, 2011

MongoDB Experiment

This example shows how to connect to a mogoDB database using the mongo-csharp-driver (git checkout). The code below demonstrates how to insert data into a collection, and retrieve a collection and deserialize the data.

using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;

namespace Console1
    internal class Program
        private static void Main(string[] args)

        private static void RunCode()
            var settings = new MongoServerSettings();
            int portNumber=999;
            settings.Server = new MongoServerAddress("", portNumber);
            settings.DefaultCredentials = new MongoCredentials("username", "password", false);
            MongoServer mongo = MongoServer.Create(settings);
            var dbSettings = new MongoDatabaseSettings(mongo, "databaseName");
            MongoDatabase mongoDb = mongo.GetDatabase(dbSettings);
            //this lists the names of the collections
            foreach (string collectoinName in mongoDb.GetCollectionNames())


            Write("Press x to exit, or any other key to Loop!");
            ConsoleKeyInfo key = Console.ReadKey();
            if (key.KeyChar != 'x')

        private static void AddCrimeTomongoDbAndReadBackTheList(MongoDatabase db)
            var crime = new Crime
                                Id = Guid.NewGuid(),
                                When = DateTime.Now,
                                Where = "Down town",
                                NatureOfCrime = "Purse snatching",
                                WitnessNames = new List {"Larry", "Curly", "Moe"}
            List crimes = db.GetCollection("Crime").FindAllAs().ToList();
            int i = 0;
            foreach (Crime c in crimes)
                Write(string.Format("item {2}: {1} (id {0})", c.Id, c.NatureOfCrime, i));

        private static void Write(string str)

    //this is a sample class which will be saved into mongoDB
    public class Crime
        public Guid Id { get; set; }
        public string NatureOfCrime { get; set; }
        public string Where { get; set; }
        public DateTime When { get; set; }
        public List WitnessNames { get; set; }

No comments: