英文:
Node Mongoose Seperate Indexes for Seperate Queries
问题
可以我们为同一集合上的完全不同的查询创建完全独立的索引吗?
我想要为用户检索其活动创建一个高效的查询,类似这样的索引:
index{ userDBID: 1 }
示例查询:
ActivityModel.find({ userDBID }).lean();
我还想要为整个应用程序统计信息创建一个单独的高效查询,该查询还需要获取活动数据,但需要使用不同的复合索引,类似这样:
index{season: 1, matchID: 1}
示例查询:
ActivityModel.find({ season, matchID }).lean()
ActivityModel.find({ season }).lean();
我发现很难找到一个坚实的高质量答案。我知道hint()似乎是一个解决方案,但我对它持怀疑态度。
Daniel
英文:
Can we create completely separate indexes for completely separate queries on the same collection?
I want an efficient query for users retrieving their activities using an index like so
index{ userDBID: 1 }
Example query
ActivityModel.find({ userDBID }).lean();
I want a separate efficient query for entire app statistics which gets activities also, but needs use a separate compound index like so
index{season: 1, matchID: 1}
Example queries
ActivityModel.find({ season, matchID }).lean()
ActivityModel.find({ season }).lean();
I am finding it hard to find a solid high-quality answer. I know hint() seems to be a solution, but I am sceptical about that one.
Daniel
答案1
得分: 2
Of course you can.
You can just add:
schema.index({ userDBID: 1 });
schema.index({ season: 1, matchID: 1 });
right after your schema declaration, before saving the Model with mongoose.model('Model', schema);
.
You will see (after a while) the new schema added in the DB. If you use an inspection tool like MongoDB Compass
you'll even have a visual representation.
I am using this efficiently in a production app so I am certain of this (just today's usage):
英文:
Of course you can.
You can just add:
schema.index({ userDBID: 1 });
schema.index({ season: 1, matchID: 1 });
right after your schema declaration, before saving the Model with mongoose.model('Model', schema);
.
You will see (after a while) the new schema added in the DB. If you use an inspection tool like MongoDB Compass
you'll even have a visual representation.
I am using this efficiently in a production app so I am certain of this (just today's usage):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论