我如何将项目添加到json对象内的数组并将其保存到使用C#的mongodb中

时间:2019-06-05 08:05:35

标签: c# mongodb

我正在尝试将json项目添加到json对象中存在的数组中,以使用c#将其保存在mongodb上 我有这个元素

    {
       "_id" : ObjectId("5cf67ad97739bfe8525e5353"),
       "Email" : "eyal@gmail.com",
       "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")
        }
    ]
}

我想使用c#将令牌项添加到令牌数组

我有这段代码查询所请求的商品

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

新项目应该是这样

 {
    "_id" : ObjectId("5cf67ad97739bfe8525e5353"),
    "Email" : "eyal@gmail.com",
    "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")
   }
]
}

2 个答案:

答案 0 :(得分:1)

您可以使用AddToSetdocs here)方法将项目原子添加到对象数组中

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

答案 1 :(得分:0)

除非您要执行一些复杂的字符串操作,否则您必须首先对其进行反序列化。例如:

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)

使用Json.net:https://www.newtonsoft.com/json