mongodb安装与使用

1. mongodb安装,以Windows Server 2008 x86_64平台为例
直接下载安装包,安装后加入到环境变量,并运行如下命令以服务的方式启动:
假定数据文件放到 D:\MongoDatabase
安装:mongod.exe --install --dbpath "D:\MongoDatabase" --serviceName "MongoDB"  --logpath "D:\MongoDatabase\MongoDB.log" --logappend 
卸载:mongod.exe --remove --serviceName "MongoDB"

2. C#调用方法
a. 官网下载.net驱动
   MongoDB.Bson.dll
   MongoDB.Driver.dll
   
b. 引用项目中

//初始化
private MongoDatabase mydb = null;
MongoClientSettings settings = new MongoClientSettings();
settings.MaxConnectionPoolSize = 3000;
settings.MinConnectionPoolSize = 300;            
settings.MaxConnectionLifeTime = TimeSpan.FromSeconds(40000);
settings.ConnectionMode = ConnectionMode.Direct;
settings.WaitQueueSize = 50;
settings.WaitQueueTimeout = TimeSpan.FromSeconds(40000);

//设置服务器的ip和端口 
string host = "127.0.0.1";
int port = 27017;
MongoServerAddress ipaddress = new MongoServerAddress(host, port);
settings.Server = ipaddress;  

MongoClient client = new MongoClient(settings);        

//创建数据库链接
MongoServer server = client.GetServer(); 

//其他参数类似
string dataBase = "local";

mydb = server.GetDatabase(dataBase);

调用示例:

数据体:
  public class LocationCache
  {

      public ObjectId _id;

      public UInt64 Number;
      public decimal Lng;
      public decimal Lat;
      public bool IsValid;
  }

//写入
  MongoCollection collection = mydb.GetCollection("LocationCache"); 
  LocationCache location = new LocationCache();
  location.Number = 123456789;
  location.Lng = 0.003267f;
  location.Lat = 0.000113f;
  collection.Insert(location);
  
  //创建索引
  collection.CreateIndex("Number");
  
  //读取
  MongoCollection collection = mydb.GetCollection("LocationCache");
  UInt64 key = 123456789;
  IMongoQuery query = Query.EQ("Number", key);
  LocationCache local = collection.FindOne(query);

你可能感兴趣的:(大数据,缓存)