Looking for way to directly query a MongoDB index, instead of the collection that the index belongs to.
For example, here are two collections:
User:
{
id: ObjectId(),
username: string
...
}
SpecialUser:
{
id: ObjectId(),
specialUsername: string
...
}
Now, let's assume that we have a unique index on the SpecialUser.specialUsername field.
We want to find the id(s) of all User documents which have their username appear in the SpecialUser.specialUsername field.
Now, we can easily do this with the following query:
db.User.aggregate([
{ $lookup: {from: "SpecialUser", localFieldName: "username", foreignField: "specialUsername", as "spUser"} },
{ $unwind: { path: "$spUser", preserveNullAndEmptyArrays: false} },
{ $project: {_id: 1}}
])
However, in this particular case, we are using a lookup and therefore fetching the SpecialUser collection although we don't need any information from that particular collection.
Is it possible to directly use the unique index instead of the $lookup operation for this particular case?