1

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful. Thanks Mick it worked :). Its really really tricky unless you get a good grip in Mongo query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.