MongoDB map-reduce-Mongo shell and C # (lower)

Source: Internet
Author: User
Tags mongo shell

Following the previous article, this article is mainly implemented by the C # version of Mongo map-Reduce. If you are not familiar with the C # driver, it doesn't matter. The MongoDB official website has a good getting started article, you will soon learn how to write the Mongo program in C #, instead of entering commands on the console every day. Getting Started
With the CSHARP driver.

Let's go back to the subject,

II. C # version:

1. construct object class record. CS:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace TestApp{    /// <summary>    /// The Class of Record    /// </summary>    public class Record    {        /// <summary>        /// The Customer Id        /// </summary>        public int cusid { get; set; }                /// <summary>        /// The Price        /// </summary>        public int price { get; set; }    }}

2. Compile mongodbhelper. CS: Some Common Operations

using System;using System.Collections.Generic;using System.Linq;using System.Text;using MongoDB.Driver;namespace TestApp{    /// <summary>    /// The Class of MongoDBHelper: common operation for MongoDB    /// </summary>    public class MongoDBHelper    {        /// <summary>        /// Get the specific db instance        /// </summary>        /// <param name="connectionString">The connect string</param>        /// <param name="dbName">DB name</param>        /// <returns>The DB instance</returns>        public static MongoDatabase GetDatabase(string connectionString, string dbName)        {            var client = new MongoClient(connectionString);            var server = client.GetServer();            MongoDatabase database = server.GetDatabase(dbName);            return database;        }    }}

3. Implement the map-Reduce program:

    class Program    {        /// <summary>        /// Insert test data to records collection in db        /// </summary>        /// <param name="records">The records instance</param>        static void InsertTestDataToRecords(MongoCollection<Record> records)        {            records.Insert<Record>(new Record() { cusid = 1, price = 15 });            records.Insert<Record>(new Record() { cusid = 2, price = 30 });            records.Insert<Record>(new Record() { cusid = 2, price = 45 });            records.Insert<Record>(new Record() { cusid = 3, price = 45 });            records.Insert<Record>(new Record() { cusid = 4, price = 5 });            records.Insert<Record>(new Record() { cusid = 5, price = 65 });            records.Insert<Record>(new Record() { cusid = 1, price = 10 });            records.Insert<Record>(new Record() { cusid = 1, price = 30 });            records.Insert<Record>(new Record() { cusid = 5, price = 30 });            records.Insert<Record>(new Record() { cusid = 4, price = 100 });            records.Insert<Record>(new Record() { cusid = 3, price = 10 });        }        static void Main(string[] args)        {            #region Test MongoDB Map-Reduce            // Connection string format: mongodb://[username:password@][host][:port]/[database]            var connectionString = "mongodb://Kevin:123456@localhost:27017/admin";            string dbName = "admin";            var db = MongoDBHelper.GetDatabase(connectionString, dbName);            var records = db.GetCollection<Record>("records");            InsertTestDataToRecords(records);            // Write map and reduce function            string mapFunction = @"function(){                                        emit(this.cusid, this.price);                                    };";            string reduceFunction = @"function(cusid, prices){                                        var total = 0;                                        total = Array.sum(prices);                                        return { sum: total };                                    };";            // Execute map-reduce method            var cusid_prices_results = records.MapReduce(mapFunction, reduceFunction);            // Print results            Console.WriteLine("Print the results of executing MapReduce method:\r\n");            foreach (var item in cusid_prices_results.GetResults())            {                Console.WriteLine(item.ToString());            }            Console.ReadKey();            #endregion        }    }

Execution result:

The result is the same as that of Mongo shell in the previous article. So far, the map-reduce application of MongoDB is here, I will continue to update more features and knowledge about MongoDB later. Thank you!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.