在mongoDB 3.6.3版本中,有一个$toString的替代方案,可以将'_id'从ObjectId()类型转换为字符串吗?

问题描述 投票:1回答:1

我正在执行一个聚合,使用$lookup来连接3个集合,基于$match条件,这涉及到匹配一个'_id'值的列表,我已经在Python中作为一个列表,与ObjectId("")版本的ObjectId("")相匹配,这是存在于mongoDb.在4.0版本中,$toString是一种方式,但我不能找到一个合适的替代方法。

criteria = [
        {
            '$project': {
                '_id': {
                    '$toString': '$_id'
                }
            }
        },
        {
            '$lookup': {
                'from': 'clients',       # other table name
                'localField': 'clientId',   # name of users table field
                'foreignField': '_id',  # name of userinfo table field
                'as': 'client_info'  # alias for userinfo table
            }
        },
        # $unwind used for getting data in object or for one record only
        {'$unwind': '$client_info'},
        # Join with job_info table
        {
            '$lookup': {
                'from': 'jobs',
                'localField': 'jobId',
                'foreignField': '_id',
                'as': 'job_info'
            }
        },
        {'$unwind': "$job_info"},
        # conditions willl go here
        {
            '$match': {
                '$and': [{'_id': {'$in': pipline_array}}]
            }
        },
        {
            '$project': {
                '_id': 1,
                'client_name': "$client_info.name",
                'job_name': "$user_role.name",
            }
        }
    ]
python mongodb mongodb-query pymongo
1个回答
1
投票

如果你想让你的聚合查询转换成 stringObjectId() 或反之亦然,那么你需要使用MongoDB的>=版本。4.0 - 的操作符,其中你会有 $toObjectId() &amp。$toString() 来进行转换。但是如果你的MongoDB版本是< 4.0 那么除了转换& 更新一个集合的所有文档中的字段,使之与另一个集合中的字段类型相匹配外,你将别无选择。

但你的问题是不同的,因为你传入的是一个字符串列表& 比较它与 _id 使用 $in因此,你可以将 stringObjectId() & 传入如下输入。

from bson.objectid import ObjectId


pipline_array = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']
pipline_array_converted = []


for i in pipline_array:
    pipline_array_converted.append(ObjectId(i))
© www.soinside.com 2019 - 2024. All rights reserved.