MongoDB and C#

本文介绍如何使用MongoDB进行数据存储和查询。从安装到第一个项目的全过程,包括C#项目的集成及LINQ支持。通过一个博客系统的例子,展示了文档数据库的优势。
Introduction

Most likely you have used a relational database and been fairly happy with it. I know I have. Be it SQL Server or MySQL, I know how to use my tools efficiently to push, pull, and transform the data I need. When we sit down to analyze a project, we'll debate over the language, the servers, etc..., but we never talk about what type of database fits the problem. We always just assume we'll use a relational database. But there are a lot of problems that can exist as a result of this choice. I not only need to know my preferred language (C#, Ruby), but I also need to know SQL. In addition, there is a known impedance mismatch between a relational structure and the domain models I so carefully craft. While I do use an OR/M (nHibernate, LINQ to SQL, etc...), it simply allows me to ignore (most of the time) this problem.

So what am I getting at? Well, there are other types of databases that exist. Object-databases like db4o and other non-relational databases like Casandra or Amazon's SimpleDB provide some relief, but none really handles the problems I need fixed. I need something that is cross-language, but also that supports an object model. I need something that is highly scalable, but still fast.

As it turns out, there is another type of database. A document-database. As I looked around, there were a number of them that fit the mold. CouchDB, RavenDB, and MongoDB are the most notable ones. I settled on MongoDB because it continued to provide me dynamic query capabilities that the other two do not.

In this article, I'd like to help you get started with MongoDB, from install to your first project. In addition, I'll show a little bit about the LINQ provider and let you play with it on your own.

 

Getting MongoDB

The MongoDB site has a downloads link sitting right at the top. You'll want to download and install the one that is pertinent to your system. I am using version 1.4.2 while writing this article.

After you have downloaded it, you can simply unzip it anywhere on your box. I unzipped mine to c:\Program Files\MongoDB. In addition, you'll need to go and manually create a directory at c:\data\db. This is the default location where MongoDB stores its files. Finally, if you go back to the MongoDB directory, you can run the server by executing mongod.exe (for Windows users).

At this point, you are running the MongoDB server on localhost, port 27017. These are the defaults, and will work just fine for our test project.

There is a shell you can run to play around with the database if you'd like. I will not get into that here, but there is a tutorial on MongoDB's site if you click "Try It Out". Note that the syntax here is not C#, but rather JavaScript.

 

MongoDB Introduction

We are going to create a simple little test project that simulates a blogging system. This is a fairly well-understood paradigm, so I won't go into the details about the object model. Shown below is the entity model we'll be using.

 


  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

 

Experienced OR/M users will notice that there are no identifiers on Comment. That is because these entities do not have their own table. They are part of the Post document and stored as an array. In other words, when we fetch a Post, we pull back all of its related comments without doing anything special. This is where the impedance mismatch mentioned in the introduction goes away. There is now no difference between my entity model here and the one stored in MongoDB.

MongoDB stores its data in BSON (binary JSON). Each server has a number of databases, and each database has a number of collections. You can think of collections like you think of tables in a relational store. In our example above, we only need a single collection to model our data. We'll go ahead and call that collection "Post" for now, after our class name.

If we were to query the Post collection from the shell (after inserting some data), we'd see JSON come back representing our data. For our example, blog will be our database name. Shown below is an example of this data.

 


  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

 

A couple of things to note about the above results. First, _id is our identifier. While I think you probably figured that out, you may not know some of the ins and outs. _id will be automatically generated if you don't provide one. Since I did not when I created this record, a type of object called an ObjectId was used. This type is documented on MongoDB's site, and is fully supported by all the client-side implementations, including MongoDB-CSharp. MongoDB-CSharp also lets you specify either your own identifier, or you can use other types of auto-generated identifiers like a GUID. Second, notice how comments are stored as an array and embedded right within the Post document. As I mentioned before, we have no need of performing a join to get all the information we need about a post, it is already a part of the document.

 

The C# Project

OK, enough chit-chat. Let's build our project. The included sample project contains MongoDB.dll to reference. If you'd like to download it yourself, the project location is at http://github.com/samus/mongodb-csharp/downloads. I've included the .90 beta 1 DLL in the libs folder. There are quite a few other C# drivers out there, but so far, I believe the functionality delivered by this driver is farther along and more mature. In full disclosure, I am biased because I helped write some of the project. Any prior version will not have the LINQ support or configuration support that exists in this one. In addition, you can consult the wiki at the location above for examples and other documentation.

So, at this point, I've created a new VS2008 solution called MongoDB Blog, with a project I call MongoDBBlog.Tester. Tester is a console application. In addition, I added a reference to MongoDB.dll that we downloaded earlier from github.

 

Finally, Some Code!!!

First things first. We need to save some posts.

 


  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

 

Great. Now we have a post in our database, but those of you astute readers will notice I can't count. I shouldn't have hardcoded that value, but then I wouldn't have a reason to show you how to update. The actual character count above is 28, not 27. That's OK, it is easy to update.

 


  

  

  

  

 

 

OK, good. All is right with the world again. At this point, we can go ahead and query our posts. In the attached code, I have entered three posts at this point so our queries have a little substance to them.

LINQ is fully supported up to the limits of MongoDB. Projections, Where clauses, and ordering are all a part of our LINQ support. Joins, however, are not. This is due to a lot of reasons that go back to consistency, but we don't support Joins because MongoDB does not support Joins. Below, we'll see some simple queries.

 


  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

 

As you can see, the query capabilities of MongoDB are satisfactory. We can get what we want when we want it. We can even do some aggregation using the Map-Reduce capabilities of MongoDB.

MongoDB uses Map-Reduce to perform scalable aggregation and rollups of data. This generally involves writing some JavaScript to get it working. Below is an example of using JavaScript to sum up our word count, first using JavaScript, and then using our LINQ provider's automatic transformation.

 


  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

 

 

Summary

I hope you've seen how easy it is to get started. There is a whole lot more we can talk about, from the proper way to use a document database to the CAP theorem and how it applies. I encourage you to do some digging on your own to find out about some of these ideas. Also, play around with the sample project. Add some fields and try stuff out. It is still a work in progress and so some LINQ functionality may not work as expected. Let us know and we'll do our best to get it resolved.

We have a Google group for users to come and ask questions, at http://groups.google.com/group/mongodb-csharp. Come and participate and, if you so desire, pull down the source and start helping us out. We truly want this to be a great library for the .NET community that functions off feedback and contributions.

 

References
 
Author

Craig G. Wilson  (United States)

转载于:https://www.cnblogs.com/erwin/archive/2010/12/15/1907142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值