如何使用Mongo DB驱动程序在列表中执行更新或删除

时间:2018-11-16 20:36:19

标签: c# mongodb mongodb-query mongodb-.net-driver

我正在学习 Mongo DB ,因此我有以下疑问。请帮助

我有一个类似以下示例的课程

public class NoteUser
{
    private int userid{get;set;}
    private List<notes> notes{get;set;}
}

现在我有一个上下文类可以从数据库中读取。而且我还有一个存储库类可以从该上下文类中读取值,并且该类具有如下功能

private bool DeleteNoteByUserId(int userId, int noteId)
{
    //Here i need to delete the note which having id as noteId for user 
    //who having the id as userId
}

private bool UpdateNoteByUserId(int userId, int noteId, Note objNote)
{
    //Here i need to perform update the note with objNote which having id as 
    //noteId for user who having the id as userId
}

如何在存储库类中使用MongoDBDriver对其进行编码?

1 个答案:

答案 0 :(得分:1)

要删除注释(嵌套对象),必须使用$pull运算符并指定过滤条件。在C#中,您可以使用以下代码:

var filter = Builders<NoteUser>.Filter.Eq(x => x.userid, userId);
var update = Builders<NoteUser>.Update.PullFilter(f => f.notes, p => p.noteid == noteId);

Col.UpdateOne(filter, update);

要更新嵌套对象,可以使用$ positional operator并指定所有属性。值-1代表与过滤器部分匹配的音符。

var filter = Builders<NoteUser>.Filter.And(Builders<NoteUser>.Filter.Eq(x => x.userid, userId), 
    Builders<NoteUser>.Filter.ElemMatch(x => x.notes, f => f.noteid == noteId));

var update = Builders<NoteUser>.Update.Combine(
            Builders<NoteUser>.Update.Set(user => user.notes[-1].firstProp, note.firstProp),
            Builders<NoteUser>.Update.Set(user => user.notes[-1].another, note.another));

Col.UpdateOne(filter, update);