[英]Mongoose $search returning empty array
在 mongoose 中使用$search
時,我得到一個空數組。
圖式
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
name: { type: String },
});
studentSchema.index({ name: 'text' });
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
$搜索
const Student = require('../models/Student.Model');
(async () => {
const result = await Student.aggregate([
{
$search: {
index: 'default',
compound: {
must: [
{
text: {
query: 'Lee',
path: 'name',
fuzzy: {
maxEdits: 1,
},
},
},
],
},
},
},
]);
})();
這給了我一個空數組。 所以我嘗試了另一種語法。
const result = await Student.aggregate().search({
index: 'default',
compound: {
must: [
{
text: {
query: 'Lee',
path: 'name',
fuzzy: {
maxEdits: 1,
},
},
},
],
},
});
這也給了我一個空數組。
為了測試 model 是否正常工作,我使用了find
和filter
,並且可以看到與我期望使用$search
看到的類似結果。
let result2 = await Student.find({});
result2 = result2.filter((p) => p.name.includes('Lee'));
result2
有兩個文檔
result2: [
{ _id: 625f70ac90e916620045cab5, name: 'Brian Lee', __v: 0 },
{ _id: 625f70e39660b486c82b2011, name: 'Lee Cohen', __v: 0 }
]
更新: find
和$text
也給我上面的正確結果,但我想實現模糊搜索,我認為你不能使用find
和 $text`:
const resultsShort = await Student.find({ $text: { $search: 'Lee' } });
為什么$search
不返回這兩個文檔?
這會創建一個 $text 索引而不是 Atlas Search 索引:
studentSchema.index({ name: 'text' });
以上可以去掉。
您不能在 mongoose 架構上創建 Atlas 搜索索引,它必須在 Atlas 站點或 CLI 上設置。
要創建 Atlas 搜索索引,go 到您在雲上的數據庫。mongodb.com ->搜索-->創建搜索索引--> JSON 編輯器-->下一步--> 選擇您的集合 --> 設置索引名稱。 在這里它將是“默認”
然后設置索引:
{
"mappings": {
"dynamic":false,
"fields":{
"name":{
"analyzer":"lucene.standard",
"type":"string"
}
}
}
然后這段代碼有效。
const result = await Student.aggregate().search({
index: 'default',
compound: {
must: [
{
text: {
query: 'Lee',
path: 'name',
fuzzy: {
maxEdits: 1,
},
},
},
],
},
});
```
使用$regex
db.collection.find({
name: {
$regex: "Lee"
}
})
創建索引
db.collection.createIndex({name:"text"})
文本搜索
db.collection.find({$text: {$search: "Lee"}})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.