如何在pymongo中使用聚合管道合并字段上的两个集合,其中一个集合的字段必须首先使用regex进行编辑



我有两个集合:一个ratings集合和一个episodes集合。ratings集合有一个字段tconst,它将是一个随机的id值,每一行都是不同的(以类似于"tt19821"的形式),episodes集合有一个字段episodeLink,它将以"/title/tt19821/"的形式。

我想用pymongo连接这两个表(连接episodeLink字段和相应的episodeLink字段)。

pipeline = [{"$set": {"tconst": {"$regexFind": {"input": "$episodeLink", "regex": "/title/(.*?)/"}}}}, {"$merge": {"into": "ratings", "on": "tconst", "whenMatched": "merge", "whenNotMatched": "discard"}}]
client['data']['episodes'].aggregate(pipeline)

我得到了以下错误的代码:如何克服'无法找到索引来验证连接字段将是唯一的'错误在pymongo中使用聚合管道。我不知道我怎么能使一个列,已在管道设置成一个唯一的索引?

'找不到索引来验证连接字段是否唯一'

这个错误说你需要在on的值/属性上创建一个索引,这意味着在ratingstconst上创建一个唯一的索引,

在数据库中执行下面的命令,

db.getCollection('ratings').createIndex({ tconst: 1 }, { unique: true })

你的查询有几个问题,

  • $regexFind将产生
tconst: {
"match" : "/title/tt19821/",
"idx" : 0,
"captures" : [ 
"tt19821"
]
}

要访问一个特定的匹配,您需要使用以下操作:

  • $let声明一个变量并首先使用$firsttconst.captures获得匹配
  • $unset_id避免错误"更新匹配文档失败">
  • 是否尝试修改_id或shard key?
  • $merge
pipeline = [
{
"$set": {
"tconst": {
"$let": {
"vars": {
"t": {
"$regexFind": {
"input": "$episodeLink",
"regex": "/title/(.*?)/"
}
}
},
"in": { "$first": "$$t.captures" }
}
}
}
},
{ "$unset": "_id" },
{
"$merge": {
"into": "ratings",
"on": "tconst",
"whenMatched": "merge",
"whenNotMatched": "discard"
}
}
]

游乐场