gpt4 book ai didi

javascript - 在 Mongoose 中索引数组项

转载 作者:行者123 更新时间:2023-11-30 13:59:42 25 4
gpt4 key购买 nike

我有一个看起来像...的模式

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 ...
});

或者第三种选择?

最佳答案

我发现我想要的是 Multikey Indexing 并在 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 字段上创建一个索引,这将是一个多键索引。

这 2 种形式几乎都可以接受,并且按预期工作;不过,我更喜欢显式索引 sizes 字段的那个。

关于javascript - 在 Mongoose 中索引数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com