初始化:
static string connStr = "mongodb://127.0.0.1:27017/?safe=true"; //连接字符串
static MongoClient client = new MongoClient(connStr);
static IMongoDatabase database = client.GetDatabase("JMessage"); //数据库
static IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("Test"); //表
插入
/// <summary>
/// 插入消息(单)
/// </summary>
/// <param name="Json"></param>
public static void InsertOne(string Json)
{
MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(Json);
collection.InsertOne(document);
}
/// <summary>
/// 插入消息(多)
/// </summary>
/// <param name="Json"></param>
public static void InsertMany(string Json)
{
List<MongoDB.Bson.BsonDocument> document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<List<BsonDocument>>(Json);
collection.InsertMany(document);
}
查询
/// <summary>
/// 获取指定表所有消息
/// </summary>
/// <param name="Collection"></param>
/// <returns></returns>
public static string GetAllByCollection(string Collection)
{
var result = database.GetCollection<BsonDocument>(Collection).Find(new BsonDocument()).ToList().ToJson();
return result;
}
/// <summary>
/// 查找群成员
/// </summary>
/// <param name="GroupId"></param>
/// <returns></returns>
public static List<BsonDocument> QueryJmsgGroupMember(string GroupId)
{
var filter = Builders<BsonDocument>.Filter.Eq("groupId", GroupId);
var result = collection.Find(filter).ToList();
return result;
}
删除
/// <summary>
/// 删除成员
/// </summary>
/// <param name="Json"></param>
public static void DeleteGroupUserMapJmsg(string userName, string groupId)
{
var filter = Builders<BsonDocument>.Filter.Eq("userName", userName)& Builders<BsonDocument>.Filter.Eq("groupId", groupId);
collection.DeleteOne(filter);
}
/// 删除表
/// </summary>
/// <param name="Collection"></param>
/// <returns></returns>
public static void DeleteByCollection(string Collection)
{
database.DropCollection(Collection);
}
更新
var filter = Builders<BsonDocument>.Filter.Eq("target.username", message["target.username"].AsString) & Builders<BsonDocument>.Filter.Eq("from.username", message["from.username"].AsString) ;
var update = Builders<BsonDocument>.Update.Set("isSend", true);
collection.UpdateMany(filter, update);
分组(条件UserName ,按createTime倒序,按target.username分组,找到各分组的第一条messageId)
//条件 where
var match = new BsonDocument {
{ "target.username",UserName}
};
//排序 order
var sort = new BsonDocument {
{"createTime",-1}
};
//分组
var group = new BsonDocument {
{"_id","$target.username"},
{"messageId",new BsonDocument("$first","$messageId")},
};
var Aggregate = userMessage.Aggregate().Match(match).Sort(sort).Group(group).ToList();
foreach (var item in Aggregate)
{
var messageId = item["messageId"].AsString;
}