如何在聚合过程中将mongodb子集合的objectid转换为字符串

时间:2020-06-01 03:05:50

标签: mongodb aggregate pymongo

我有两个这样的收藏集:

# col1
[
  {
    _id: '5ec878f79c87a300127ec503',
    name: 'dim'
  },
  {...},
]
# col2
[
  {
    _id: ObjectId('5ec8da619c87a30012f41d0b'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'authenticated'
  },
  {
    _id: ObjectId('5ec8da619c87a30012ffdsk1'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'pre'
  },
]

我想将两个集合合并为一个,并将col2._id从objectid转换为字符串

这是我的汇总查询:

col1.aggregate(
  [
    {'$lookup': {
       'from': 'col2',
       'localField': '_id',
       'foreignField': 'record_id',
       'as': 'records'
    }},
    {'$project': {'records._id': {'$toString': '$records._id'}}}
  ]
)

除了我的结果应该是这样的:

# result
[
  {
    '_id': '5ec878f79c87a300127ec503',
    'name': 'dim',
    'records': [
        {
          '_id': '5ec8da619c87a30012f41d0b',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'authenticated'
        },
        {
          '_id': '5ec8da619c87a30012ffdsk1',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'pre'
        },
      ]
  }
]

但我遇到了错误。

Unsupported conversion from array to string in $convert with no onError value

我还尝试了 $ addFields $ map 。它要么覆盖记录并返回一个数组,要么创建一个新字段。那不是我想要的。

{'$addFields': {
  'records': {
    '$map': {
        'input': '$records',
        'as': 'r',
        'in': {'$toString': '$$r._id'}
      }
    }
}}

所以我的问题是:如何在聚合期间将col2._id从objectid转换为字符串?

1 个答案:

答案 0 :(得分:0)

您可以尝试下面的选项,在该选项中,我们首先将id转换为String并存储为convertedIdStr,然后使用它进行查找。

[
 {
  "$addFields": {
     "convertedIdStr": {
        "$toString": "$_id"
     }
  }
    },
 {
  "$lookup": {
     "from": "test",
     "localField": "convertedIdStr",
     "foreignField": "record_id",
     "as": "records"
  }
 }
]

希望这会有所帮助! 注意我们在col1(collection1)上运行此聚合