数组中按值分组的PouchDB/CouchDB

7uhlpewt  于 2022-12-09  发布在  CouchDB
关注(0)|答案(1)|浏览(175)

我使用的是PouchDB,我有一个数据集,它以图表的形式表示一个社交网络。人物是文档,他们关注的人是被关注者的_id数组。下面是一个数据示例:

[
    {
        "_id": "mc0001",
        "name": "Jill Martin",
        "joined": "2020-01-15",
        "follows": []
    },
    {
        "_id": "mc0002",
        "name": "Elena Markova",
        "joined": "2020-01-21",
        "follows": ["mc0001"]
    },
    {
        "_id": "mc0003",
        "name": "Carlos Sanchez",
        "joined": "2020-01-27",
        "follows": ["mc0001", "mc0002"]
    },
    {
        "_id": "mc0004",
        "name": "Ai Sato",
        "joined": "2020-02-21",
        "follows": ["mc0001", "mc0003"]
    },
    {
        "_id": "mc0005",
        "name": "Ming Wu",
        "joined": "2020-03-21",
        "follows": ["mc0002", "mc0003", "mc0004"]
    }
]

我想做的是查询每个人,并得到一个追随者的列表。我正在寻找这样的东西:

[
    {
        "_id": "mc0001",
        "followers": ["mc0002", "mc0003", "mc0004"]
    },
    {
        "_id": "mc0002",
        "followers": ["mc0003", "mc0005"]
    },
    {
        "_id": "mc0003",
        "followers": ["mc0004", "mc0005"]
    },
    {
        "_id": "mc0004",
        "followers": ["mc0005"]
    },
    {
        "_id": "mc0005",
        "followers": []
    }
]

有没有办法在不改变数据结构的情况下做到这一点(例如,将followers数组移动到被跟踪者的文档中)?

hgqdbh6s

hgqdbh6s1#

创建一个Map/Reduce视图,循环遍历每个文档中的follows数组并发出这些数组;就像这样:

function (doc) {
  for(var i =0; i<doc.follows.length; i++) {
    emit(doc.follows[i], null);
  }
  
}

最后得到一个以用户为键的索引,其中每一行都有该用户的追随者的id,然后可以查询该索引,提供要查找其追随者的用户的键,如下所示:

$URL/users/_design/users/_view/by-follower?key="mc0001"&reduce=false

你会得到这样的东西:

{"total_rows":8,"offset":0,"rows":[
{"id":"mc0002","key":"mc0001","value":null},
{"id":"mc0003","key":"mc0001","value":null},
{"id":"mc0004","key":"mc0001","value":null}
]}

这并不是您问题中的数据格式,但您可以看到每个对象中的id字段包含您所需用户的追随者,因此您可以从那里开始。

相关问题