1 安装
官方地址:http://www.mongodb.org/downloads
windows:
1.1 mongodb安装完后,启动前创建一下几个文件或者文件夹
1 数据库存储文件夹 db
2 日志文件夹 logs
3 日志文件 mongodb.log
4 配置文件文件夹 conf
5 conf 该文件夹下创建配置文件 mongo.conf
配置文件信息如下:
————————————————————————————————————————————————————————————————————————————————
dbpath=E:\WeiWork\mdb\data #存储数据文件
logpath=E:\WeiWork\mdb\logs\mongodb.log #日志输出文件路径
logappend=true #错误日志采用追加模式,配置这个选项后mongodb的日志会追加到现有的日志文件,而不是从新创建一个新文件
journal=true #启用日志文件,默认启用
quiet=true #这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为false
port=27017 #端口号 默认为27017
auth=true #启用验证 需要用户名密码
————————————————————————————————————————————————————————————————————————————————
1.2 启动cmd命令(win+R),
先进入安装目录 cd C:\Program Files\MongoDB\Server\3.4\bin
目录下文件说明:
Server(服务端) mongod.exe
Router(路由) mongos.exe
Client(客户端) mongo.exe
MonitoringTools mongostat.exe, mongotop.exe
ImportExportTools mongodump.exe, mongorestore.exe, mongoexport.exe, mongoimport.exe
MiscellaneousTools bsondump.exe, mongofiles.exe, mongooplog.exe, mongoperf.exe
设置配置文件
mongod --config " E:\WeiWork\mdb\conf\mongo.conf"\
安装Windows服务
mongod --config "E:\WeiWork\mdb\\conf\mongo.conf" --install --serviceName "MongoDB"
启动服务
net start MongoDB
访问 http://localhost:27017/
2 客户端连接:
常用cmd:
db
查看当前使用数据库
use dbname
切换数据库到指定数据库
3 测试
插入数据
db.user.insert({name:"jack"})
查找数据
db.user.find({name:"jack"})
更新数据
db.user.update({name:"2131'})
4 可视化管理工具
https://robomongo.org/download
5 .NET 调驱动
NuGet
MongoDB.Drive,MongoDB.Bson ,MongoDB.Drive.Core
测试代码:
MongoClient client = new MongoClient("mongodb://localhost");
IMongoDatabase db = client.GetDatabase("school");
var user = new User() {
Name="Weu",
Age=12
};
db.GetCollection<User>("User")
.InsertOne(user);
var list= db.GetCollection<User>("User")
.Find(c=>c.Age>10);
帮助类:
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Mongo
{
class MongoDBHelper
{
private static MongoClient client;
private static IMongoDatabase database;
//本地配置
private const string MongoDBConnectionStr = "mongodb://localhost";
//数据库名称
private static string DefaultDataBaseName = "Test";
public MongoDBHelper()
{
GetConnection(DefaultDataBaseName);
}
/// <summary>
/// 构造函数 指定数据库
/// </summary>
/// <param name="dataBaseName"></param>
public MongoDBHelper(string dataBaseName)
{
GetConnection(dataBaseName);
}
private static void GetConnection(string dataBaseName)
{
client = new MongoClient(MongoDBConnectionStr);
database = client.GetDatabase(dataBaseName);
}
/// <summary>
/// 异步插入一条数据,手动输入collection name
/// </summary>
public Task InsertAsync<T>(string collectionName, T obj)
{
if (database == null)
{
throw new Exception("没有指定数据库");
}
var collection = database.GetCollection<T>(collectionName);
return collection.InsertOneAsync(obj);
}
/// <summary>
/// 异步插入一条数据,采用类型T的完全限定名作为collection name
/// </summary>
public Task InsertAsync<T>(T obj)
{
return InsertAsync(typeof(T).FullName, obj);
}
/// <summary>
/// 异步插入多条数据,手动输入collection name
/// </summary>
public Task BatchInsertAsync<T>(string collectionName, IEnumerable<T> objs)
{
if (database == null)
{
throw new Exception("没有指定数据库");
}
if (objs == null)
{
throw new ArgumentException();
}
var collection = database.GetCollection<T>(collectionName);
return collection.InsertManyAsync(objs);
}
/// <summary>
/// 异步插入多条数据,采用类型T的完全限定名作为collection name
/// </summary>
public Task BatchInsertAsync<T>(IEnumerable<T> objs)
{
return BatchInsertAsync(typeof(T).FullName, objs);
}
/// <summary>
/// 插入一条数据
/// </summary>
public void Insert<T>(T obj)
{
InsertAsync(obj).Wait();
}
/// <summary>
/// 插入多条数据
/// </summary>
public void Insert<T>(IEnumerable<T> objs)
{
BatchInsertAsync(objs).Wait();
}
/// <summary>
/// MongoDB C# Driver的Find方法,返回IFindFluent。手动输入collection name
/// </summary>
public IFindFluent<T, T> Find<T>(string collectionName, FilterDefinition<T> filter, FindOptions options = null)
{
if (database == null)
{
throw new Exception("没有指定数据库");
}
var collection = database.GetCollection<T>(collectionName);
return collection.Find(filter, options);
}
/// <summary>
/// MongoDB C# Driver的Find方法,返回IFindFluent。采用类型T的完全限定名作为collection name
/// </summary>
public IFindFluent<T, T> Find<T>(FilterDefinition<T> filter, FindOptions options = null)
{
return Find(typeof(T).FullName, filter, options);
}
/// <summary>
/// 取符合条件的数据 sort中多个排序条件逗号分隔,默认asc
/// </summary>
public List<T> Get<T>(Expression<Func<T, bool>> condition, int skip, int limit, string sort)
{
return Get(new List<Expression<Func<T, bool>>> { condition }, skip, limit, sort);
}
public List<T> Get<T>(Expression<Func<T, bool>> condition)
{
return Get(condition, 0, 0, null);
}
/// <summary>
/// 取符合条件的数据 sort中多个排序条件逗号分隔,默认asc
/// </summary>
public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions, int skip, int limit, string sort)
{
if (conditions == null || conditions.Count == 0)
{
conditions = new List<Expression<Func<T, bool>>> { x => true };
}
var builder = Builders<T>.Filter;
var filter = builder.And(conditions.Select(x => builder.Where(x)));
var ret = new List<T>();
try
{
List<SortDefinition<T>> sortDefList = new List<SortDefinition<T>>();
if (sort != null)
{
var sortList = sort.Split(',');
for (var i = 0; i < sortList.Length; i++)
{
var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');
if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))
{
sortDefList.Add(Builders<T>.Sort.Ascending(sl[0]));
}
else if (sl.Length >= 2 && sl[1].ToLower() == "desc")
{
sortDefList.Add(Builders<T>.Sort.Descending(sl[0]));
}
}
}
var sortDef = Builders<T>.Sort.Combine(sortDefList);
ret = Find(filter).Sort(sortDef).Skip(skip).Limit(limit).ToListAsync().Result;
}
catch (Exception e)
{
//异常处理
}
return ret;
}
public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions)
{
return Get(conditions, 0, 0, null);
}
}
}