标签:
在实际开发中遇到更新某个document中的数组的值,这里做一下记录。
这里使用的驱动为
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wolfy.Mongodb { class Program { static void Main(string[] args) { } } class MongoHelper { private static readonly string _db = ""; private static readonly string _col = ""; private static readonly string _ip = ""; private static readonly string _user = ""; private static readonly string _pwd = ""; private static readonly string _connStr = string.Format("mongodb://{0}:{1}@{2}:27017/{3}", _user, _pwd, _ip, _db); /// <summary> /// 为某个userId添加friend,如果数组中不存在则添加 /// </summary> /// <param name="userId"></param> /// <param name="friendId"></param> /// <returns></returns> public static bool UpdateOrInsert(string userId, string friendId) { var col = GetCollection(); var query = new QueryDocument { { "userId", userId }, new QueryDocument { { "$nin", new BsonArray().Add(friendId) } } }; var update = Update.Push("friends", friendId).Inc("count", 1); return col.Update(query, update, UpdateFlags.None).Ok; } private static MongoCollection<BsonDocument> GetCollection() { MongoClient client = new MongoClient(_connStr); MongoServer server = client.GetServer(); var db = server.GetDatabase(_db); var col = db.GetCollection(_col); return col; } /// <summary> /// 从属性中移除好友 /// </summary> /// <param name="userId"></param> /// <param name="friendId"></param> /// <returns></returns> public static bool RemoveFriend(string userId, string friendId) { var col = GetCollection(); var query = new QueryDocument { { "userId", userId } }; MongoDB.Driver.Builders.UpdateBuilder builder = new MongoDB.Driver.Builders.UpdateBuilder(); builder.Pull("friends", friendId); return col.Update(query, builder, UpdateFlags.None).Ok; } /// <summary> /// 更新字段值 /// </summary> /// <param name="userId"></param> /// <param name="dic"></param> /// <returns></returns> public static bool UpdateFields(string userId, Dictionary<string, object> dic) { var col = GetCollection(); var query = new QueryDocument { { "userId", userId } }; MongoDB.Driver.Builders.UpdateBuilder builder = new MongoDB.Driver.Builders.UpdateBuilder(); foreach (var item in dic.Keys) { builder.Set(item, BsonValue.Create(dic[item])); } builder.Set("dt", DateTime.Now); return col.Update(query, builder, UpdateFlags.Upsert).Ok; } } }
代码
上述是好友列表中的操作。如果好友列表中已经存在,则不再添加,否则添加。省略用c#在做业务的判断了。其实有很多,都可以交给mongodb去做,可以在代码中少很多的if-else。
标签:
原文地址:http://www.cnblogs.com/wolf-sun/p/5607986.html