'Optimizing query that makes 3 API calls to the MongoDB server

const user_schema = mongoose.Schema(
  {
    user_name: {
      type: String,
      required: true,
    },
  },
  {
    collection: `user`,
    timestamps: true,
  }
);


const test_schema = mongoose.Schema(
  {
    test_name: {
      type: String,
      required: true,
    },
  },
  {
    collection: `test`,
    timestamps: true,
  }
);

const score_schema = mongoose.Schema(
  {
    user_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "user",
      required: true,
    },
    test_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "test",
      required: true,
    },
    test_score: {
      type: Number,
      required: true,
    },
  },
  {
    collection: `score`,
    timestamps: true,
  }
);

query:

Given an array of user_id and an array of test_id, query the score model to find out the test scores. To get the array of user_id, a set of conditions is given and the user model must be queried to find the set of users matching the conditions. To get the array of test_id, a set of conditions is given and the test model must be queried to find the set of tests matching the conditions.

What needs to be done:

  1. Make one query request to the MongoDB server to get the array of user_id.
  2. Make a separate query request to the MongoDB server to get the array of test_id.
  3. Make another query request to the MongoDB server to get the test scores:
db.getCollection("score").aggregate([
  {$match: {$and: {user_id: {$in: array_of_user_id}, {test_id: {$in: array_of_test_id}}}}}
])

Is this the most optimal way to get the test scores? Is it possible to make just one request to the MongoDB server?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source