json - 操作 Redis JSON 中的嵌套对象数组

标签 json redis node-redis redisjson redislabs

我有一个带有嵌套数组的 JSON,如下所示,要保存在 Redis 中。我正在使用 RedisJSON 模块将数据保存为 JSON。

customer:12345 : {
    info : {
        key1: val1,
        key2: val2,
        key3: val3
    },
    rides: [
        {
            rideid: xxx,
            from: fromval,
            to: toval,
            date: dateofride,
            distance: distanceval,
            points: pointsval
        },
        {
            rideid: yyy,
            from: fromval,
            to: toval,
            date: dateofride,
            distance: distanceval,
            points: pointsval
        },
        ...
    ]
}

我有一种情况,可以将新项目添加到数组中或可以编辑现有项目。我正在使用带有express.js的node-redis客户端。 Express 应用程序仅接收在行程数组中更改或添加的数据。如果该项目已在数组中,则新数据必须替换现有的数组项目(rideid 是每个对象的键),否则必须将其添加到数组中。我如何实现这一目标?

最佳答案

给定以下 JSON 文档

{
    "info": {
        "key1": "val1"
    },
    "rides": [{
            "rideid": "xxx",
            "points": 0
        },
        {
            "rideid": "yyy",
            "points": 10
        }
    ]
}

由 RedisJSON 中的 key customer:12345 使用以下命令保存

127.0.0.1:6379> JSON.SET customer:12345 . "{\"info\": {\"key1\": \"val1\",\"key2\": \"val2\",\"key3\": \"val3\"},\"rides\":[{\"rideid\": \"xxx\",\"points\": 0 },\t{\"rideid\": \"yyy\",\"points\": 10}]}"

您可以使用rideid yyy更新行程,例如将分数增加 5,如下

127.0.0.1:6379> JSON.NUMINCRBY customer:12345 "$.rides[?(@.rideid=='yyy')].points" 5
"[15]"

$.rides[?(@.rideid=='yyy')].points 是一个 JSONPath 表达式(更多 herehere ,还回答了 here )

添加新行程

127.0.0.1:6379> JSON.ARRAPPEND customer:12345 $.rides "{\"rideid\": \"zzz\",\"points\": 5 }"
1) (integer) 3

所有RedisJSON命令都可以在 here 找到

关于json - 操作 Redis JSON 中的嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70640933/

相关文章:

javascript - 使用 Javascript 的多个日期时间之间的平均天数

c# - 将没有属性名称的 Json 解析为 C#

ruby - 如何使用 Redis 在 Sinatra 中存储 session 值?

node.js - 如何理解node_redis中的参数?

redis - 如何在不同端口的单个服务器上运行 redis?

javascript - 在 Google map API 中创建条形图

ios - 使用 Swift 解包 Yahoo API

redis - 如何在redis中模式匹配空字符串?

node.js - Array.push,数组保持为空

node.js - Redis 发布/订阅限制