C#与mongoDB初始环境搭建
mongoDB官网https://www.mongodb.com/
mongoDB默认安装路径(Windows x64平台)
C:\Program Files\MongoDB\Server\3.4\bin
mongoDB环境变量配置
启动mongoDB服务
> mongod -dbpath D:\mongodb
> mongo
Visual Studio引用mongoDB
PM> install-package MongoDB.Driver
C#操作详见
https://docs.mongodb.com/ecosystem/drivers/csharp/
string url = "mongodb://127.0.0.1:27017";
var client = new MongoClient(url);
var db = client.GetDatabase("blog");//获取数据库,如果不存在就创建一个
var collection = db.GetCollection<Post>("post");
//增
//for(int i = 1; i < 10000; i++) {
// Post post = new Post()
// {
// Id = i,
// Author = "作者" + i,
// CreateTime = DateTime.Now,
// Issue = false,
// Title = "文章" + i,
// Details = Guid.NewGuid().ToString(),
// Comments = new List<string>() { "评论" + i }
// };
// collection.InsertOne(post);
//}
//查
// Console.WriteLine(collection.CountDocuments(c => 1 == 1));
// var p5 = collection.Find(p => p.Id == 5).First();
// Console.WriteLine("{0}在{1}发表了{2}", p5.Author, p5.CreateTime, p5.Title);
//删
// collection.FindOneAndDelete<Post>(p => p.Id == 6);
//var p6 = collection.Find<Post>(p => p.Id == 6).FirstOrDefault();
//改
// var filter = Builders<Post>.Filter.Eq("Id", 7);
// var update = Builders<Post>.Update.Set("Title", "夏天");
//collection.FindOneAndUpdate<Post>(filter, update);
//var p7 = collection.Find(f => f.Id == 7).FirstOrDefault();
// Console.WriteLine("{0}在{1}发表了{2}", p7.Author, p7.CreateTime, p7.Title);
配置mongoDB服务
在mongoDB的安装目录下创建配置文件mongod.cfg,然后再配置文件中添加服务的日志的输出路径(对路径没有强制要求)
systemLog:
destination: file
path: D:\mongodb\logs\mongodb.log
storage:
dbPath: D:\mongodb\data
通过管理员打开cmd.exe
> mongod --config "D:\mongoDB\mongod.cfg" --install --serviceName "MongoDB"