可以使用MongoDB的全文搜索功能来执行包含文本的查询。以下是使用Mongoose库进行全文搜索查询的示例代码:
npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.log(error));
const articleSchema = new mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
});
articleSchema.index({ title: 'text', content: 'text' }); // 创建文本索引
const Article = mongoose.model('Article', articleSchema);
const searchText = 'example'; // 搜索关键字
Article.find({ $text: { $search: searchText } })
.then(articles => console.log(articles))
.catch(error => console.log(error));
在上面的示例中,我们创建了一个包含title
和content
字段的Article
模型,并使用index
方法为这两个字段创建了一个文本索引。然后,我们使用$text
操作符和$search
关键字来执行全文搜索查询。查询结果将返回匹配搜索关键字的所有文章。
请注意,要使用全文搜索功能,您需要使用MongoDB版本3.2或更高版本,并且必须在集合中至少创建一个文本索引。