Click here to Skip to main content
15,880,392 members
Articles / Database Development / NoSQL

Using MongoDB with the Official C# Driver

Rate me:
Please Sign up or sign in to vote.
4.87/5 (28 votes)
24 Oct 2011CPOL6 min read 152.1K   3.9K   55  
Introduces how to use MongoDB in your ASP.NET MVC project using the official C# driver.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroMongo.Models;

using MongoDB.Bson;

namespace IntroMongo.Controllers
{
    public class RemarkController : Controller
    {
        public ActionResult Index(string id)
        {
            // Get remarks by id
            var user = MongoWrapper.GetDatabase().
                            GetCollection("users").
                            FindOneByIdAs<User>(ObjectId.Parse(id));

            return View(user);
        }

        [HttpPost]
        public ActionResult Index(string id, string newRemark)
        {
            var users = MongoWrapper.GetDatabase().GetCollection("users");
            var user = users.FindOneById(ObjectId.Parse(id));

            var remark = new BsonDocument().
                                Add("content", newRemark).
                                Add("date", DateTime.Now);

            if (user.Contains("remarks"))
            {
                user["remarks"].AsBsonArray.Add(BsonValue.Create(remark));
            }
            else
            {
                user["remarks"] = new BsonArray().Add(BsonValue.Create(remark));
            }

            users.Save(user);

            return RedirectToAction("Index", new { id = id });
        }
    }
}

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
Software Developer
Turkey Turkey
I am interested in innovation and creativity in software development and passionate in learning new stuff.

Comments and Discussions