【问题标题】:MongoDB / Mongoose - Text search inside arrayMongoDB / Mongoose - 数组内的文本搜索
【发布时间】:2020-07-15 02:15:30
【问题描述】:

我需要在数组元素中执行文本搜索。有可能吗?

在 Node.js 中使用 Mongoose,我的 userSchema 如下所示:

{
 _id: "123456",
 name: "Lucas"
 items: [
  { title: "Shoes", description: "Very nice shoes"}, 
  { title: "Pants", description: "Great pants!"}
 ]
}

我尝试像这样添加索引:

userSchema.index({ "items.title": "text", "items.description": "text" });

但是下面的查询什么也不返回:

User.find({  $text: { $search: "Shoes" }});

【问题讨论】:

  • mongo shell 尝试时它工作正常。在“Shoes”上的文本搜索将匹配 titledescription 字段,其中文本值“Shoes”和“... nice shoes”是匹配项。
  • 你能返回任何记录吗?例如试试 User.find()

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

mongoose 不是索引管理解决方案。所以不要依赖猫鼬来创建索引。他们甚至在faq 的文档中声明了这一点。

在生产环境中,您应该使用 MongoDB shell 而不是依赖 mongoose 为你做这件事。

所以你需要做的就是在 mongodb shell 中创建文本索引。 如果集合名称与 users 不同,您还需要在下面进行更改。

db.users.createIndex(
    {
        "items.title": "text",
        "items.description": "text",
    }
)

【讨论】:

  • 就是这样!完美!
【解决方案2】:

对我来说,它与 @typegoose 索引装饰器一起使用。

@index({
    _id: "text",
    name: "text",
    items: "text",
    "items.title": "text",
    "items.description": "text",
})
export class User {
    @prop({ required: true }) public name: string;
    @prop({ required: true }) public items: Array<ItemInterface>;
}

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2016-05-28
    • 2012-03-26
    相关资源
    最近更新 更多