I actually resolved this issue, however, posting here as a question in hope someone will find the solution useful. I was looking for a purely MongoDB query/aggregation that would serve as a batch getter for FB's DataLoader. I didn't want to .map()
afterwards on the server, so the query result had to be an object with keys being the ids, and the values being the documents themselves.
Asked
Active
Viewed 137 times
0

gazorpazorp
- 468
- 3
- 13
1 Answers
0
const resMapArr = db.SOMECOLLECTION.aggregate([{
$match : {
_id: { $in: _ids }
}
}, {
$group: {
_id: null,
docs: { $push: "$$ROOT" }
}
}, {
$project: {
res: {
$arrayToObject: {
$map: {
input: "$docs",
as: "el",
in: {
k: { $convert: { input: "$$el._id", to: "string" }},
v: "$$el"
}
}
}
}
}
}, {
$replaceRoot: { newRoot: "$res" }
}
])
const resMap = resMapArr[0];
This way you can return the results in DataLoader's batch function as:
return _ids.map(id => resMap[id.toHexString()] || null);

gazorpazorp
- 468
- 3
- 13