eyal berda
eyal berda

Reputation: 9

how can i add an item to an array inside json object and save it to mongodb using c#

I am trying to add a json item to an array exist in json object to save it on mongodb using c# i have this element

    {
       "_id" : ObjectId("5cf67ad97739bfe8525e5353"),
       "Email" : "[email protected]",
       "Username" : "eyal",
       "Password" : "1234",
       "Tokens" : [ 
        {
            "Tokennumber" : "123",
            "Valid" : "true",
            "LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
        }, 
        {
            "Tokennumber" : "124",
            "Valid" : "false",
            "LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
        }
    ]
}

i want to add a token item to tokens array using c#

i have this code querying the requested item

var client = new MongoDB.Driver.MongoClient();
var db = client.GetDatabase("SupaFoo");
var _users = db.GetCollection<Users>("Users");
var user =
(from u in _users.AsQueryable<Users>()
where u.email == login.Email && u.password == login.Password
 select u).ToList();

the new item sholud be like this

 {
    "_id" : ObjectId("5cf67ad97739bfe8525e5353"),
    "Email" : "[email protected]",
    "Username" : "eyal",
    "Password" : "1234",
    "Tokens" : [ 
    {
        "Tokennumber" : "123",
        "Valid" : "true",
        "LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
    }, 
    {
        "Tokennumber" : "124",
        "Valid" : "false",
        "LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
    },
    {/* newly added item */
        "Tokennumber" : "555",
        "Valid" : "true",
        "LoginDate" : ISODate("2019-06-05T00:00:00.000Z")
   }
]
}

Upvotes: 0

Views: 247

Answers (2)

Skami
Skami

Reputation: 1576

You can atomically add items to an objects array using the AddToSet (docs here) method

        var updateDefinition = Builders<Users>.Update.AddToSet(x => x.Tokens, new Token());
        var filterDefinition = Builders<Users>.Filter.Eq(x => x.Id, userId);

        _users.UpdateOne(filterDefinition, updateDefinition);

Upvotes: 1

vsarunov
vsarunov

Reputation: 1547

I am afraid you have to deserialize it first, unless you want to do some complex string manipulation. For example:

var user= JsonConvert.DeserializeObject<User>(yourJson);
user.Tokens.Add(new Token());
var _users = db.GetCollection<Users>("Users"); // if you have this initialized before re-use it
var filter = Builders<User>.Filter.Eq(s => s.Id, user.Id);
var result = await collection.ReplaceOneAsync(filter, user)

This using Json.net: https://www.newtonsoft.com/json

Upvotes: 0

Related Questions