【问题标题】:MongoDB text search doesn't search single wordMongoDB 文本搜索不搜索单个单词
【发布时间】:2022-12-22 05:05:15
【问题描述】:

所以我想在我的 MongoDB 数据库中搜索我的博客集合。我想按标题搜索,我在模式文件中用 mongoose 创建了索引。一切都很好,但是如果我有一个博客的标题是这样的:“averylongtitlewithoutspaces”,除非我输入整个标题,否则它不会搜索它。它适用于空格,因此搜索“非常”会返回“带空格的非常长的标题”。如何让 mongo 搜索带空格的文本?

这是我的架构文件

import { Schema, model } from "mongoose";

interface IBlog {
    title: String,
    content: String,
    author: String,
    authorId: Schema.Types.ObjectId,
    shortContent: String,
    image: String
}


const BlogSchema = new Schema<IBlog>({
    title: {
        required: true,
        type: String
    },
    content: {
        required: true,
        type: String
    },
    author: {
        required: true,
        type: String
    },
    authorId: {
        required: true,
        type: Schema.Types.ObjectId,
        ref: "Account"
    },
    shortContent: {
        required: true,
        type: String
    },
    image: {
        requred: true,
        type: String
    }


}, { 
    timestamps: true
}); 
BlogSchema.index({ title: "text" }, {default_language: "none"});


export const Blog = model("Blog", BlogSchema, "blogs");

我正在做的查询:

    const blogs = await Blog.find({ $text: { $search: req.params.input } });

【问题讨论】:

  • 请添加您正在进行的查询。
  • @Ayzrian 补充说,抱歉我完全忘记了。
  • 您可以使用 {name:/.*sam.*/} 等正则表达式进行搜索

标签: node.js mongodb mongoose


【解决方案1】:

在您的查询中添加双引号。例如:

{"$text":{"$search":""hello world""}}

请注意,您不能将正则表达式用于文本字段/索引。

(如果您正在处理 Web 内容,请务必注意 %20s...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多