Node Mongoose 为不同查询分别创建索引

huangapple go评论80阅读模式
英文:

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):

http://prntscr.com/qj1n2o

英文:

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):

http://prntscr.com/qj1n2o

huangapple
  • 本文由 发表于 2020年1月3日 22:23:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定