优化对 MongoDB 服务器进行 3 个 API 调用的查询
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,
}
);
查询:
给定一个 user_id 数组和一个 test_id 数组,查询 score
模型以找出测试分数。 要获取user_id
数组,需要给出一组条件,并且必须查询user
模型以找到匹配条件的用户集。 要获取 test_id
数组,需要给出一组条件,并且必须查询 test
模型以查找与条件匹配的测试集。
需要做什么:
- 向 MongoDB 服务器发出一个查询请求以获取
user_id
数组。 - 向 MongoDB 服务器发出单独的查询请求以获取
test_id
数组。 - 向 MongoDB 服务器发出另一个查询请求以获取测试分数:
db.getCollection("score").aggregate([
{$match: {$and: {user_id: {$in: array_of_user_id}, {test_id: {$in: array_of_test_id}}}}}
])
这是获取测试分数的最佳方式吗?是否可以只向 MongoDB 服务器发出一个请求?
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:
- Make one query request to the MongoDB server to get the array of
user_id
. - Make a separate query request to the MongoDB server to get the array of
test_id
. - 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论