使用Mongoose索引数组项

5

我有一个类似于以下结构的模式...

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
    }],
    // other properties ...
});

我执行形如 Items.find({ sizes: { $elemMatch: 'someSize' } }); 的查询操作。
因此,我想在元素中添加索引以便快速执行该查询。

应该像下面这样:

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
        index: true,
    }],
    // other properties ...
});

或者

const itemSchema = new Schema({
    sizes: {
        type: [{
            type: String,
            enum: [/* some fixed sizes */],
        }],
        index: true,
    },
    // other properties ...
});

或许还有第三种选择?
4个回答

9
我发现我想要的东西叫做多键索引,并在MongoDB找到了相关文档。
根据文档,对于类型为数组的字段进行索引将为数组的每个字段创建一个索引,这些索引都指向同一个文档,这正是我想要优化查询的地方。
因此,正确的答案应该是:
const itemSchema = new Schema({
    sizes: {
        type: [{
            type: String,
            enum: [/* some fixed sizes */],
        }],
        index: true,
    },
    // other properties ...
});

但是经过实验和使用指南针检查索引集合后,我发现这个问题可能与索引有关。

const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: [/* some fixed sizes */],
        index: true,
    }],
    // other properties ...
});

同样的方式也适用于第二种表单,并将在sizes字段上创建一个多键索引。

所以这两种形式都是可接受的,而且按预期工作;不过我更喜欢显式索引sizes字段的方式。


2
你可以像这样在类型声明中定义索引

最初的回答
const itemSchema = new Schema({
    sizes: [{
        type: String,
        enum: ['foo', 'bar'],
        index: true,
    }],
    // other properties ...
});

你也可以像@Eduardo提到的那样,通过类似以下方式在事后定义它们:@Eduardo mention之后的内容可以通过以下方式定义:
itemSchema.index({ _id: 1 }, { sparse: true });

所有内容都在文档中。最初的回答。

我考虑过这个问题,但不确定它是否可行,谢谢。 - Amr Saber

0

这不完全是我想要的,我想索引数组内部对象,而不是数组本身。 - Amr Saber

0
扩展@Amr Saber和@Akrion的答案,
如果有人想要定义默认或必需值,
const itemSchema = new Schema({
    sizes: [{ 
      type: [{
         type: String,
         enum: [/* some fixed sizes */],
         index: true,
      }],
      required: true, 
      default: [] 
    }],
    // other properties ...
});

可以使用。对我来说似乎很好用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接