将Json字符串存储为C#中的MongoDB数组

时间:2018-09-28 07:50:33

标签: mongodb linq asp.net-core mongodb-query mongodb-csharp-2.0

我想将一个JSON字符串以数组格式存储在MongoDB中。这是我的C#代码,用于将通知存储到MongoDB中,此处的“ Event_meta”字段以JSON字符串格式发送到MongoDB。

[27/Sep/2018:16:23:37 +0100] <request IP> - - - <requested URI>  to: [::1]:5001: GET /api/hc response_status 200
[27/Sep/2018:16:24:37 +0100] <request IP> - - - <requested URI>  to: 127.0.0.1:5001: GET /api/hc response_status 200
[27/Sep/2018:16:25:38 +0100] <request IP> - - - <requested URI>  to: localhost: GET /api/hc response_status 502
[27/Sep/2018:16:26:37 +0100] <request IP> - - - <requested URI>  to: 127.0.0.1:5001: GET /api/hc response_status 200
[27/Sep/2018:16:27:37 +0100] <request IP> - - - <requested URI>  to: [::1]:5001: GET /api/hc response_status 200

“ eventmsg.Event_meta”是动态类型。“ Event_meta”值以jsonstring的形式存储在MongoDB中。但是我想将其存储为Array格式。

public async Task Handle(TaskPropertyUpdatedEvent eventmsg)
        {
        try
        {
            var meta = JsonConvert.SerializeObject(eventmsg.Event_meta);
            var notificationEvent = new Notifications()
            {
                Content = eventmsg.Content,
                Type = "TaskEvent",
                UserId = eventmsg.UpdatedById,
                EntityId = eventmsg.TaskId.ToString(),
                AddedDate = eventmsg.UpdatedDate,
                Active = true,
                ShowNotification = false,
                InternalEvent = true,
                UserName = eventmsg.UpdatedByName,
                Event_type = eventmsg.Event_type,
                Event_meta = meta

            };
            var result = await _eventRepository.AddEventAsync(notificationEvent);              
        }

        catch (Exception ex)
        {


        }

    }

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使您的Event_meta字段类型进入BsonDocument并反序列化为BsonDocument。 或将您的Notifications类设置为Mongo Doc

这样的映射器类