C# Mongo驱动 易忘方法

1.查询实体Model内 List<SonModel> sonModels内字段。

public SonModel GetSonModel(string modelId, string sonModelId){var query = Query.And(Query<Model>.EQ(m => m.Id, modelId),Query<Model>.ElemMatch<SonModel>(m => m.SonModels , q => q.EQ(a => a.Id, sonModelId)));var result = this.GetCollection().Find(query).SetFields("sonmodel.$");var model = result.SingleOrDefault();if (model == null) return null;var list = model.Folders.ToList();return list.Count > 0 ? list[0] : null;}

对应查询语法

{"_id" : ObjectId("53b294ecc10a332eb8f652af"),"SonModels" : { "$elemMatch" : { "Id" : "具体子编号" } } }

2.添加以及删除Model内 List<SonModel> sonModels内某条记录

/// <summary> /// 添加单条sonModel /// </summary> /// <param name="Number"></param> /// <param name="Pictures"></param> /// <returns></returns> public bool AddPic(string Number, PicDto Picture) { var query = Query<ADDto>.EQ(q => q.Number, Number); Picture.Id = ObjectId.GenerateNewId().ToString(); var update = Update<ADDto>.AddToSet(q => q.Pictures, Picture); var result = this.GetCollection().Update(query, update); return result.Ok; }
 /// <summary> /// 删除单条SonModel /// </summary> /// <param name="Number"></param> /// <param name="PicId"></param> /// <returns></returns>public bool DelPic(string Number, string PicId) { ObjectId oid = ObjectId.Empty; if (!ObjectId.TryParse(PicId, out oid)) return false; var query = Query<ADDto>.EQ(q => q.Number, Number); var update = Update<ADDto>.Pull(m => m.Pictures, q => q.EQ(c => c.Id, PicId)); var result = this.GetCollection().Update(query, update); return result.Ok && result.DocumentsAffected > 0; }

其中update 对应的json语法

{ "$addToSet" : { "pictures" : { "_id" : ObjectId("5440caef2c9364045cde3a48"), "PictureUrl" : "/file/ad/543b386b87508b53006781db.jpg", "Name" : "阿水博客", "JumpUrl" : "Http;//ashui.net", "StartTime" : ISODate("2014-10-17T07:47:00Z"), "EndTime" : ISODate("2014-10-17T07:47:00Z"), "shopproductid" : null, "hits" : 232, "weight" : 0, "area" : [1, 2, 3] } } }