Python MongoDB聚合以在字段之间进行选择
我有一个MongoDB集合,其中包含可选的原始字段Age、YOB和DOB,以及这些字段的标准化版本(如果存在):Python MongoDB聚合以在字段之间进行选择,python,mongodb,mongodb-query,aggregation-framework,pymongo,Python,Mongodb,Mongodb Query,Aggregation Framework,Pymongo,我有一个MongoDB集合,其中包含可选的原始字段Age、YOB和DOB,以及这些字段的标准化版本(如果存在): {'_id': 123, 'Age': '30.0', 'DOB': '1990-01-01', 'Standardized_Age_from_Age_field': 30, 'Standardized_Age_from_DOB_field': 30}, {'_id': 123, 'Age': '21', 'DOB': 'xx/xx/xxxx', 'Standardized_Age_
{'_id': 123, 'Age': '30.0', 'DOB': '1990-01-01', 'Standardized_Age_from_Age_field': 30, 'Standardized_Age_from_DOB_field': 30},
{'_id': 123, 'Age': '21', 'DOB': 'xx/xx/xxxx', 'Standardized_Age_from_Age_field': 21, 'Standardized_Age_from_DOB_field': null},
{'_id': 123, 'Age': '19', 'YOB': '119', 'Standardized_Age_from_Age_field': 19, 'Standardized_Age_from_YOB_field': 119},
...
我需要创建一个最终字段Age\u standarized
,该字段将在这三个可选字段中选择最正确的字段。例如,如果来自年龄字段的标准化年龄为19,而来自年龄字段的标准化年龄为119,则最终的标准化年龄将为19。或者,如果来自年龄字段的标准化年龄为25,并且来自年龄字段的标准化年龄或来自性别字段的标准化年龄均不存在,则它将输出年龄标准化25
在PyMongo中,有没有一种方法可以在聚合框架中干净地实现这一点?我的选择标准基本上是:
如果存在标准化的DOB,标准化的DOB不为空,标准化的DOB为整数或可以成功转换为整数(例如,DOB为'19'或DOB为19.0或DOB为19),则将Age_标准化设置为标准化的DOB
否则,如果存在标准化YOB,标准化YOB不为空,标准化YOB为整数或可以成功转换为整数(例如,YOB为'19'或YOB为19.0或YOB为19),则将年龄设置为标准化YOB
否则,如果存在标准化年龄,标准化年龄不为空,标准化年龄为整数或可以成功转换为整数(例如,年龄为'19'或年龄为19.0或年龄为19),则将标准化年龄设置为标准化年龄
否则就不会产生标准化年龄
聚合管道的开始:
cursor = self.db.aggregate([
{'$match': {
'meta.State': d['state'],
'meta.City': d['city'],
'$or': [
{'DOB_Age_Standardized': {'$exists': True}},
{'YOB_Age_Standardized': {'$exists': True}},
{'Age_Age_Standardized': {'$exists': True}},
]
}},
{
# see if Standardized_Age_from_DOB_field can be extracted to Age_Standardized as an integer between 13 and 98, else
# see if Standardized_Age_from_YOB_field can be extracted to Age_Standardized as an integer between 13 and 98, else
# see if Standardized_Age_from_Age_field can be extracted to Age_Standardized as an integer between 13 and 98, else
# do not capture Age_Standardized because none of the 3 above fields can be extracted as an integer between 13 and 98
# delete any of the above fields present in the documents in the collection and make sure each document only contains an Age_Standardized field
}