Mongo 批量过滤并添加连接字段
Mongo bulk filter and add concatenated field
我有一个要更新的 Mongo 集合(在 PyMongo 中)。我有像 {'state': 'ny', 'city': 'nyc', 'race': 'b', 'ethnicity': 'h'}
这样的文档,我正在尝试通过匹配某些条件并创建一个串联的 'race_ethnicity' 字段来对这些文档进行批量操作。
伪示例可能是:
filter = {
'state': 'ny',
'city': 'nyc',
'race': {"$exists": True},
'ethnicity': {"$exists": True},
'race_ethnicity': {"$exists": False}
}
action = {'$addFields': {'race_ethnicity': {'$concat': ['$race', '$ethnicity']}}}))
使用上述文档,更新后的文档为:{'state': 'ny', 'city': 'nyc', 'race': 'b', 'ethnicity': 'h', 'race_ethnicity': 'bh'}
.
我想像这样批量匹配和批量更新集合 — 如何在不出现 BulkWriteError 的情况下执行此操作?
*** 我试过的:
updates = []
updates.append(UpdateMany({
'state': 'ny',
'city': 'nyc',
"race": {"$exists": True},
"ethnicity": {"$exists": True},
"race_ethnicity": {"$exists": False}
},
{'$addFields': {'race_ethnicity': {'$concat': ['$race', '$ethnicity']}}}))
self.db.bulk_write(updates)
这产生了以下错误:
pymongo.errors.BulkWriteError: batch op errors occurred
- 根据 bulkWrite() syntax、
,您的批量写入负载不正确
$addFields
是您不能在常规更新查询中使用的聚合管道阶段,因此要解决此问题您可以使用 update with aggregation pipeline 从 MongoDB 4.2 开始,
updates = []
updates.append({
'updateMany': {
'filter': {
'state': 'ny',
'city': 'nyc',
'race': { '$exists': True},
'ethnicity': { '$exists': True},
'race_ethnicity': { '$exists': False}
},
'update': [
{
'$set': { 'race_ethnicity': { '$concat': ['$race', '$ethnicity'] } }
}
]
}
})
self.db.bulk_write(updates)
我有一个要更新的 Mongo 集合(在 PyMongo 中)。我有像 {'state': 'ny', 'city': 'nyc', 'race': 'b', 'ethnicity': 'h'}
这样的文档,我正在尝试通过匹配某些条件并创建一个串联的 'race_ethnicity' 字段来对这些文档进行批量操作。
伪示例可能是:
filter = {
'state': 'ny',
'city': 'nyc',
'race': {"$exists": True},
'ethnicity': {"$exists": True},
'race_ethnicity': {"$exists": False}
}
action = {'$addFields': {'race_ethnicity': {'$concat': ['$race', '$ethnicity']}}}))
使用上述文档,更新后的文档为:{'state': 'ny', 'city': 'nyc', 'race': 'b', 'ethnicity': 'h', 'race_ethnicity': 'bh'}
.
我想像这样批量匹配和批量更新集合 — 如何在不出现 BulkWriteError 的情况下执行此操作?
*** 我试过的:
updates = []
updates.append(UpdateMany({
'state': 'ny',
'city': 'nyc',
"race": {"$exists": True},
"ethnicity": {"$exists": True},
"race_ethnicity": {"$exists": False}
},
{'$addFields': {'race_ethnicity': {'$concat': ['$race', '$ethnicity']}}}))
self.db.bulk_write(updates)
这产生了以下错误:
pymongo.errors.BulkWriteError: batch op errors occurred
- 根据 bulkWrite() syntax、 ,您的批量写入负载不正确
$addFields
是您不能在常规更新查询中使用的聚合管道阶段,因此要解决此问题您可以使用 update with aggregation pipeline 从 MongoDB 4.2 开始,
updates = []
updates.append({
'updateMany': {
'filter': {
'state': 'ny',
'city': 'nyc',
'race': { '$exists': True},
'ethnicity': { '$exists': True},
'race_ethnicity': { '$exists': False}
},
'update': [
{
'$set': { 'race_ethnicity': { '$concat': ['$race', '$ethnicity'] } }
}
]
}
})
self.db.bulk_write(updates)