Reputation: 63
I am performing an aggregation which is performing joins using $lookup to join 3 collections based on a $match condition which involves matching a list of '_id' values which I already have available as a list in python to that of ObjectId("") version that is present in mongoDb. In version 4.0 $toString is the way to go but i cannot find a suitable alternative for this
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",
}
}
]
Upvotes: 2
Views: 1129
Reputation: 17915
If you wanted your aggregation query to convert string
to ObjectId()
or vice-versa on the fly by itself then you need to use MongoDB version >= 4.0
- where you'll have operators $toObjectId()
& $toString()
to do the conversion. But if your MongoDB version is < 4.0
then you'll have no option other than to convert & update your field in all documents of one collection to match with type of field in other collection.
But your issue is different, as you're passing in a list of strings & comparing it against _id
using $in
, So instead you can convert string
to ObjectId()
& pass-in as input like below :
from bson.objectid import ObjectId
pipline_array = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']
pipline_array_converted = []
for i in pipline_array:
pipline_array_converted.append(ObjectId(i))
Upvotes: 2