【问题标题】:Mongodb: splite string in aggregation pipelineMongodb:聚合管道中的拆分字符串
【发布时间】:2018-02-07 11:48:22
【问题描述】:

这是我存储到集合中的文档:

{
    "_id" : UUID("61a2053c-1a79-4649-8793-df6c4dc1973"),
    "NotificationId" : UUID("ad068e4e-10e2-528c-a74a-df6c4dd9211"),
    "DistributionId" : UUID("f5445ea1-e6cb-4acd-9881-c4122df6c4d"),
    "CreationDateTime" : ISODate("2016-07-13T04:20:38.697Z"),
    "ExpirationDateTime" : ISODate("2099-01-01T00:00:00.000Z"),
    "DeliveryType" : 1,
    "DeliveryParams" : [],
    "Address" : "Topics/Messages/Global",
    "Payload" : "{\"Id\":\"ad067896-10e2-528c-er87-df6c4d123654\",\"CreationDateTime\":\"\\/Date(1468324824751)\\/\",\"DeviceId\":\"456987456985\",\"UserId\":\"64545678-1234-4834-4321-123456789012\",\"UserFullName\":\"test-user\",\"SystemId\":\"com.messaging\",\"SystemTitle\":\"message\",\"EventId\":\"messaging.message\",\"EventTitle\":\"ارسال پیام\",\"EventData\":[],\"BusinessCode\":\"1-2-4-4-5-6-9\",\"ProcessId\":\"55333333-4433-3333-7733-113333333399\",\"WorkItemId\":423458,\"WKT\":\"\"}",
    "SendAttempts" : null,
    "Sent" : ISODate("2016-11-10T10:01:22.140Z"),
    "Delivered" : ISODate("1970-01-01T00:00:00.000Z")
}

我的问题是,我怎么能在里面拆分\"BusinessCode\":\"1-2-4-4-5-6-9\" 有效负载字段。我只需要 BusinessCode:1-2-4-4-5-6-9 来存储到另一个字段。

我使用了这个脚本:

db.Messages.find().forEach(function(item)
{
    id = item._id;
    payload = item.Payload;
    matched = payload.match(/\"BusinessCode\":\"(([1-2]?[0-9])-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*))\"/);
....
db.Messages.updateOne(
....

这个payload.match返回

BusinessCode":"1-2-4-4-5-6-9",1-2-4-4-5-6-9,1,2,4,4,5,6,9

此脚本不适合多文档收集,速度慢。我想使用聚合管道。

我如何才能在聚合管道中获得与 payload.match 完全相同的响应?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    从 3.6.2 开始,我们在 mongo 中没有正则表达式子字符串

    我们可以使用 substr 方法对业务 id 进行子串化,由于 payload 包含 unicode 字符,我们需要使用 CodePoint (CP) 来获得预期的结果

    db.col.aggregate(
        [
            {$addFields : {
                    start : {$indexOfCP : ["$Payload", "BusinessCode"]},
                    end : { $indexOfCP : ["$Payload", "ProcessId"]}
                }
            },
            {$project : {BusinessCode : {$substrCP : ["$Payload", {$sum : ["$start",15]}, {$subtract : [{$subtract : ["$end", "$start"]}, 18]}]}}}
        ]
    )
    

    结果

    { "_id" : "61a2053c-1a79-4649-8793-df6c4dc1973", "BusinessCode" : "1-2-4-4-5-6-9" }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-08
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多