I want to query some specific non-consecutive indexes of an array in a MongoDB document.
The options I have considered are:
- Query the entire array, then filter by index in client script. This isn't viable as for a large array it will result in fetching unwanted items from the database (Suppose I need only index 5 and 20, but there are actually 1000 items in the array).
- Using $slice multiple times picking every time each of the indices I want from the array. But this results in N number of calls.
- Instead of a simple array, I can use a child schema where every item in the array has an assigned Id, and while querying, I can use "find" to select those specific ids. But this adds an extra "id" field which I do not want. I am sure there must be a way to pick items by the array index.
I am looking for a more elegant solution where I can pick certain specific indices from the array in a single operation.
Example document in Quiz model:
{
questions: [
{
text: "Question 1",
answer: "Answer 1",
},
{
text: "Question 2",
answer: "Answer 2",
},
...
...
{
text: "Question 1000",
answer: "Answer 1000",
},
]
}
I want something in the lines of:
const questions = await Quiz.find({
questions: {
$index_in: [10, 42, 66]
}
}).exec();
Expected output:
[
{
text: "Question 10",
answer: "Answer 10",
},
{
text: "Question 42",
answer: "Answer 42",
},
{
text: "Question 66",
answer: "Answer 66",
},