替代MongoDB最大索引密钥长度?

时间:2014-12-16 17:16:53

标签: mongodb express mongoose

我试图在我的应用程序中添加搜索功能,其中我使用的是MongoDB(2.6.6),Mongoose(3.8.8)和ExpressJs(4.7.2)。

我使用以下方法使我的集合中的某些字段可转换。

UserSchema.index({
  field1: 'text',
  field2: 'text',
  field3: 'text',
  field4: 'text',
  field5: 'text',
  field6: 'text'
});

但事实证明,根据MongoDB documentation,这个索引确实有一个最大长度。 当我只有5个字段时,搜索工作完美,但是当我添加第6个字段时,似乎我达到了最大长度。并且未创建索引。

我在搜索中使用类似的东西:

User.find({ $text: { $search: 'foo' }})

我用它来检查索引:

db.users.getIndexes()

那么解决这个问题的最佳方法是什么?有没有其他方法可以进行此搜索?

谢谢!

1 个答案:

答案 0 :(得分:0)

我不确定你为什么要编制索引并找到那种方式,除非我错过了什么。

对于您正在执行的复合索引,您最多可以包含31个字段:http://docs.mongodb.org/manual/reference/limits/

使用Mongoose,您应该像这样索引:

var userSchema = new Schema({ email: { type: String, required: true, index: true }, password: { type: String, required: true }, first_name: { type: String, required: true, index: true }, last_name: { type: String, required: true, index: true }, accessToken: { type: String, index: true }, created: { type: Date, default: Date.now, index: true }, provider: { type: String, index: true } });

userSchema.index({email: 1, first_name: 1, last_name: 1, accessToken: 1, created: -1, provider: 1}) //1 or -1 depending on how to sort your index

最后搜索,只需:

User.find({email: 'rahat@me.com'}, function(err, data) ...)

OR多个字段:

User.findOne({first_name: 'Rahat', last_name: 'Mahbub'}, function(err, data) ...)

参考:http://mongoosejs.com/docs/guide.html#indexes

http://docs.mongodb.org/manual/core/indexes-introduction/