c# - Updating Dictionary in Mongodb -
i have class stores following data:
public class user { public objectid _id { get; set; } public string name { get; set; } public string pass { get; set; } public dictionary<string, tuple<string, string>> quests { get; set; } } new users instantiated this:
await collection.insertoneasync(new user { name = u, pass = p, quests = new dictionary<string,tuple<string,string>>() }); i know how find , pull information created documents, don't know how push , save changes documents. of answers online old mongodb c# driver, things query or .save() don't exist, or didn't include right packages program.
i want able add , remove entries dictionary , save changes document. suggestions?
not sure want. there 2 types of updates in mongodb: can perform atomic update, or replace document.
replacing document easier, because allows use standard c# operations perform modifications , re-evaluate generated properties , like:
var user = new user { name = "john doe", quests = new dictionary<string, tuple<string, string>> { { "hoho", new tuple<string, string>("a", "a-item") } } }; users.insertoneasync(user).wait(); user.quests = new dictionary<string, tuple<string, string>> { { "hoho modified", new tuple<string, string>("b", "b-item") } }; users.replaceoneasync(p => p.id == user.id, user); however, required use atomic modifiers, $push, $pull, $set, $addtoset, etc. because of concurrency concerns. consider bad idea perform complex operations on complex embedded objects way, because there high likelihood object's consistency (in acid sense, or 'object invariants') can't checked.
suppose user should not allowed have more 3 active quests @ time, ensures rule observed? code's responsibility, , complex invariants can't checked database.
if still want use atomic operators, suggest ask new question because there depends on details (the dictionary, default, serialized document, tuple array, , require different atomic modifiers in mongodb). example, add new item dictionary, use $set:
users.updateoneasync(p => p.id == user.id, builders<user>.update.set("quests.hoho modified", new tuple<string, string>("b", "b-item")));
Comments
Post a Comment