I have the following query:
db.getCollection('authors').aggregate([
{ $match: {} },
{ $sort: { name: -1 } },
{ $addFields: { x_id___as___string: { $toString: "$_id" } } },
{ $lookup: {
from: "books",
let: { fkField:"$x_id___as___string" },
pipeline: [{ $match: { $expr: { $in: ["$$fkField", "$authorIds"] } } }],
as: "books"
}
}
])
which works fine, unless the authorIds array is missing from some of the joined documents, in which case I get the error of
"errmsg" : "$in requires an array as a second argument, found: missing", "code" : 40081, "codeName" : "Location40081" } : aggregate failed
I've confirmed that manually adding authorIds as an empty array to the documents missing it fixes the query. My question is:
How can I adjust this query to work with a non-existent authorIds field?
Should I change my $expr to be an $and query, with the first value a check for array existence? Does Mongo guarantee short-circuiting? Is there a simpler check I can just add to the $in query?