设为首页 收藏本站
查看: 1024|回复: 0

[经验分享] mongodb配置及应用实例

[复制链接]

尚未签到

发表于 2015-7-8 06:34:08 | 显示全部楼层 |阅读模式
  mongodb的文章园中却已不少,看过的文章也已不少,很多东西眼高手低,一直也没有应用过,看的再多,步入实际应用下,虽早已深深知道,但苦于自己懒散...
  练习.练习....做个记录..
  mongbdb是文档型数据库(nosql),可以到http://www.mongodb.org/downloads下载对应版本,这里用的是win下32位的,下载后解压,可以看到bin目录下有很有exe文件,我把文件放到了I盘,并重启名字MongoDB,新建文件夹data(后面会用到),如图
DSC0000.jpg
  现在打开命令行窗口并切换到mongo存放目录,mongod启动服务,如图
DSC0001.jpg
  这里用到了--dbpath data指定数据文件存放的目录,这就是前面新建的data文件夹,它不会自动创建,如果不指定存放路径(--dbpath data)仅用mongod启动,需要在当前盘符的根目录创建data/db文件夹,它会自动查找,当看到最后的端口号就说明启动成功了!
  当然每次启动都比较麻烦,可以定制成windows服务,我们在data文件夹下创建俩个子文件夹如图
DSC0002.jpg
  
  以管理员身份打开命令行窗口并切换到mongodb所在目录,执行命令如图
  
DSC0003.jpg
  --directoryperdb说明是否为每一个数据库创建一个文件夹,最后--install安装(注意设置--logpath时要指定一个.log文件,不存在会自动创建)。
  看到 command line via 'net start "MongoDb"'说明定制成功,输入
  net start MongoDB启动服务
  net stop MongoDB停止服务
  sc delete MongoDB删除服务或运行→regedit→注册表编辑器→HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services找到相应服务删除即可
  现在打开http://127.0.0.1:27017/可以看到
DSC0004.jpg
  也可以打开http://127.0.0.1:28017/看一些服务端状态信息
  扯了这么多还是直接实例来操作数据库吧,这里我用的是c#驱动,光c#就有很多种,很多人都喜欢用samus驱动,因为支持linq语法,这里也选择此驱动,下载地址https://github.com/samus/mongodb-csharp
  如果下载的直接是.dll文件添加引用即可,如果是源码,编译下在引用.dll即可,目录结构
DSC0005.jpg
  Customer



namespace mytest
{
public class Customer
{
[MongoId]
public string CustomerID { get; set; }
public string CustomerName { get; set; }
[MongoIgnore]
public string Address { get; set; }
}
}

  CustomerBLL



namespace mytest
{
public class CustomerBLL
{
public static void Insert(Customer customer)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Insert(customer);
}
}
public static void Delete(string customerId)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Remove(x => x.CustomerID == customerId);
}
}
public static void Update(Customer customer)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Update(customer, (x => x.CustomerID == customer.CustomerID));
}
}
public static Customer GetById(string customerId)
{
using (MGHelper mm = new MGHelper())
{
return mm.GetCollection().FindOne(x => x.CustomerID == customerId);
}
}
}
}
  MGHelper



namespace mytest
{
public class MGHelper : IDisposable
{
private Mongo _mongo;
private IMongoDatabase _db;
public MGHelper()
: this("Server=127.0.0.1", "test")
{
}

public MGHelper(string connectionString, string dbName)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString");
_mongo = new Mongo(connectionString);
_mongo.Connect();
if (string.IsNullOrEmpty(dbName) == false)
_db = _mongo.GetDatabase(dbName);
}
public IMongoDatabase UseDb(string dbName)
{
if (string.IsNullOrEmpty(dbName))
throw new ArgumentNullException("dbName");
_db = _mongo.GetDatabase(dbName);
return _db;
}
public IMongoDatabase CurrentDb
{
get
{
if (_db == null)
throw new Exception("当前连接没有指定任何数据库。请在构造函数中指定数据库名或者调用UseDb()方法切换数据库。");
return _db;
}
}
///
/// 获取当前连接数据库的指定集合【依据类型】
///
///
///
public IMongoCollection GetCollection() where T : class
{
return this.CurrentDb.GetCollection();
}
///
/// 获取当前连接数据库的指定集合【根据指定名称】
///
///
/// 集合名称
///
public IMongoCollection GetCollection(string name) where T : class
{
return this.CurrentDb.GetCollection(name);
}
public void Dispose()
{
if (_mongo != null)
{
_mongo.Dispose();
_mongo = null;
}
}
}
}

  Program演示增加功能



namespace mytest
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.CustomerID = 1 + "";
customer.CustomerName = "GM0";
customer.Address = "测试";
CustomerBLL.Insert(customer);
customer.CustomerID = 2 + "";
customer.CustomerName = "GM1";
CustomerBLL.Insert(customer);
}

}
}

  这里用了园友的DBHelper操作类,更多详细介绍http://www.iyunv.com/fish-li/archive/2011/06/26/2090800.html
  执行过后如何查看结果呢,mongodb提供了Javascript shell
DSC0006.jpg
  相应命令都很直译,就不解释了...
  mongodb的索引



namespace mytest
{
class Program
{
static void Main(string[] args)
{
TestMongodb tm = new TestMongodb();
tm.InsertMongo();
tm.Start();
Console.ReadLine();
}
}
public class TestMongodb
{
private Mongo mongo;
private MongoDatabase mongoDatabase;
private MongoCollection mongoCollection;
public TestMongodb()
{
mongo = new Mongo("mongodb://localhost");
mongoDatabase = mongo.GetDatabase("testDB") as MongoDatabase;
mongoCollection = mongoDatabase.GetCollection("testCollection") as MongoCollection;
mongo.Connect();
}
~TestMongodb()
{
mongo.Disconnect();
}
//插入数据
public void InsertMongo()
{
var random = new Random();
TimeSpan span = new TimeSpan(DateTime.Now.Ticks);
for (int i = 0; i < 100000; i++)
{
Document doc = new Document();
doc["ID"] = i;
doc["Data"] = "data" + random.Next(10000);
mongoCollection.Save(doc);
}
TimeSpan span1 = new TimeSpan(DateTime.Now.Ticks);
string op = string.Format("执行了{0}秒,共插入{1}条数据", span1.Subtract(span).Duration().Seconds, mongoCollection.FindAll().Documents.Count());
Console.WriteLine(op);
}
//删除数据
public void RemoveMongo()
{
mongoCollection.Remove(x => true);
}
//创建索引
public void CreateIndex(string index)
{
mongoCollection.Metadata.CreateIndex(new Document() { { "_" + index + "_", 1 } }, false);
}
//删除索引
public void DropIndex(string index)
{
mongoCollection.Metadata.DropIndex("_" + index + "_");
}
//排序
public void SortForData()
{
mongoCollection.FindAll().Sort(new Document() { { "Data", 1 } });
}
public void Start()
{
Stopwatch watch = new Stopwatch();
watch.Start();
SortForData();
Console.WriteLine("无索引排序时间:" + watch.Elapsed);
CreateIndex("Data");
Stopwatch watch1 = new Stopwatch();
watch1.Start();
SortForData();
Console.WriteLine("有索引排序时间:" + watch1.Elapsed);
}
}
}

  测试截图
DSC0007.jpg
  有关索引的说明文章http://www.iyunv.com/lipan/archive/2011/03/28/1997202.html
  关于文件存取的操作参考http://www.iyunv.com/lipan/archive/2011/03/21/1989409.html
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84200-1-1.html 上篇帖子: MongoDB的备份方式 下篇帖子: MongoDB学习笔记(一)MongoDB概述和安装
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表