Mongo 4 Realese (Edit)
you can use $addfield
and $toObjectId
and lookup on that newfield
first your A collection have a proplem , change it to
{
“b_id" : ObjectId("532a234234….”),
“c_id" : ObjectId(“532fdf….”),
“d_id”: ObjectId("532fdf….")
}
for test u to see result
u can use Robo3t to see colection information (not necessary but help a lot )
in mongoShell u can join this 4 collection like this
db.A.aggregate([
{"$lookup" :
{
"from" : "B",
"localField" : "b_id",
"foreignField" : "_id",
"as" : "b_info"
}
},
{"$unwind" :"$b_info"}, // if u want can ignore this line
{"$lookup" :
{
"from" : "C",
"localField" : "c_id",
"foreignField" : "_id",
"as" : "c_info"
}
},
{"$unwind" :"$c_info"}, // if u want can ignore this line
{"$lookup" :
{
"from" : "D",
"localField" : "d_id",
"foreignField" : "_id",
"as" : "d_info"
}
},
{"$unwind" :"$d_info"}, // if u want can ignore this line
])
now for python u can exatcly run mongo command with pymongo
first install it with pip
then in your code
from pymongo import MongoClient
client = MongoClient('localhost', 27017) # change Address and port if not use local host
db = client.DBNAME # change DBNAME to your DBNAME
result = list(db.A.aggregate([
{"$lookup" :
{
"from" : "B",
"localField" : "b_id",
"foreignField" : "_id",
"as" : "b_info"
}
},
{"$unwind" :"$b_info"}, # if u want can ignore this line
{"$lookup" :
{
"from" : "C",
"localField" : "c_id",
"foreignField" : "_id",
"as" : "c_info"
}
},
{"$unwind" :"$c_info"}, # if u want can ignore this line
{"$lookup" :
{
"from" : "D",
"localField" : "d_id",
"foreignField" : "_id",
"as" : "d_info"
}
},
{"$unwind" :"$d_info"}, # if u want can ignore this line
]))
Edit (convert string to ObjectId)
first solution is before create Json create their ObjectID (if you have paralel or async there is very very very low chance too create 2 same ObjectID and faild to insert as you know value object id generated by time stamp)
from bson import objectid
b_id = objectid.ObjectId()
c_id = objectid.ObjectId()
d_id = objectid.ObjectId()
objB["_id"] =b_id
objC["_id"] = c_id
objD["_id] = d_id
objA["b_id"] = b_id
objA["c_id"] = c_id
objA["d_id"] = d_id
# insert 4 into DB here
second way u already create A just need to convert string into ObjectID:
from bson import objectid
# objA it what u want to insert in A collection
for key in objA:
objA[key] = objectid.ObjectId(objA[key])
db.A.save(objA)