$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,
},
},
},
],
},
});
這也給了我一個空陣列。
為了測驗模型是否正常作業,我使用了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退回這兩個檔案?
uj5u.com熱心網友回復:
這將創建一個 $text 索引而不是 Atlas Search 索引:
studentSchema.index({ name: 'text' });
上面的可以去掉。
您不能在 mongoose 架構上創建 Atlas Search 索引,它必須在 Atlas 站點或 CLI 上設定。
要創建 Atlas 搜索索引,請轉到 cloud.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,
},
},
},
],
},
});
```
uj5u.com熱心網友回復:
采用$regex
db.collection.find({
name: {
$regex: "Lee"
}
})
mongoplayground
創建索引
db.collection.createIndex({name:"text"})
文本搜索
db.collection.find({$text: {$search: "Lee"}})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/462410.html
標籤:javascript 节点.js mongodb 猫鼬 聚合框架
上一篇:CastError:模型“XXXX”的路徑“_id”處的值“XXXXXXXXXX”(型別字串)轉換為ObjectId失敗
下一篇:一次更新多個檔案
