Reputation: 21
I created a ref collection which contains other collection name and document id.
So it looks like
{
refName: "Collection 1",
refId: "123123",
},
{
refName: "Collection 2",
refId: "456734",
}
Collection 1 and Collection 2 have the documents with id 123123 and 456734. In this case, I wanna loop all ref collection and get referenced collection data using mongodb aggregation.
I tried to use $lookup but it is said that $from of $lookup must be string literals, not the variables.
Is there anyway to handle this kind of transaction in MongoDB?
Upvotes: 2
Views: 354
Reputation: 8894
You can convert string to int or int to string
db.ref.aggregate([
{
$addFields: {
refId: {
"$toInt": "$refId"
}
}
},
{
"$lookup": {
"from": "coll1",
"localField": "refId",
"foreignField": "_id",
"as": "join"
}
}
])
Working Mongo playground String to Int
Working Mongo playground Int to String withUncorrelated-sub-queries
Upvotes: 1