Search code examples
c#mongodbmongodb-querymongodb-.net-driver

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


I was learning Mongo DB and in that i have following doubt. Please help

I have a class like following example

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

And now i have a context class to read from the database. And i also have one repository class to read the values from this context class, and this class have the functions like following

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
}

How do i code it using MongoDBDriver in my repository class?


Solution

  • To delete a note (nested object) you have to use $pull operator and specify filtering condition. In C# you can use following code:

    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);
    

    To update nested object you can use $ positional operator and specify all properties. Value -1 represents the note that is matched by filter part.

    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);