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

How to perform Update or Delete in list using Mongo DB Driver

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

我有一个 class 像下面的例子

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

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

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
}

如何使用我的存储库 class 中的 MongoDBDriver 对其进行编码?

要删除注释(嵌套对象),您必须使用 $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);