Reputation: 391
Inside my existing pipeline, I wanna get a sample of 10 documents from another collection (another collection different than the one that the pipeline is targeted at).
I could do this with $lookup, but it would perform this search in other collection one time for every individual record in the main pipeline, and this could greatly decrease the performance.
The final result would be something similar to the one with lookup, but without the server load of performing one lookup for every single record. It would be kinda like a general lookup ran only once for the query.
Is it possible?
Here's the code I have so far, but it performs multiple lookups, one for each record in the main collection, which gives me poor performance that tends to get worse as the amount of documents in the original collection grows
{
$facet: {
array1: [
{
$match: {
_id: req.params.id,
},
},
],
array2: [
{
$match: {
$expr: {
$ne: ["$_id", req.params.id],
},
},
},
],
array3: [
{
$lookup: {
from: "external_collection",
pipeline: [{ $sample: { size: 10 } }],
as: "random_suggestions",
},
},
{
$project: {
_id: 0,
random_suggestions: 1,
},
},
],
}
}
Upvotes: 0
Views: 96