mongoose多條件模糊查詢實例


mongoose多條件模糊查詢

這是今天手頭項目中遇到的一個問題,關於mongoose如何實現類似於SQL中 nick LIKE '%keyword%' or email LIKE '%keyword%' 這種多條件模糊搜索的問題。 查閱了mongoose文檔才得以實現,特此記錄一下。

mongodb文檔

mongoose文檔

主要用到了query.$or和query.$regex這兩個find參數。

其中query.$or用於實現多條件查詢,其值是一個數組。相關文檔

示例代碼:

query.or([{ color: 'red' }, { status: 'emergency' }])

query.$regex用於實現模糊查詢。相關文檔

示例代碼:

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

通過以上兩個參數就可以實現多條件模糊查詢了。以User表為例,通過輸入一個關鍵字,來匹配昵稱或者郵箱與關鍵字相近的記錄。

示例代碼:

const keyword = this.params.keyword //從URL中傳來的 keyword參數
const reg = new RegExp(keyword, 'i') //不區分大小寫
const result = yield User.find(
    {
        $or : [ //多條件,數組
            {nick : {$regex : reg}},
            {email : {$regex : reg}}
        ]
    },
    {
        password : 0 // 返回結果不包含密碼字段
    },
    {
        sort : { _id : -1 },// 按照 _id倒序排列
        limit : 100 // 查詢100條
    }
)

實例代碼

 var local = require('./models/local')

 app.get('/local/repeat', function (req, res) {
 var keyword = req.query.keyword // 獲取查詢的字段

 var _filter={
    $or: [  // 多字段同時匹配
      {cn: {$regex: keyword}},
      {key: {$regex: keyword, $options: '$i'}}, //  $options: '$i' 忽略大小寫
      {en: {$regex: keyword, $options: '$i'}}
    ]
  }
  var count = 0
  local.count(_filter, function (err, doc) { // 查詢總條數(用於分頁)
    if (err) {
      console.log(err)
    } else {
      count = doc
    }
  })

  local.find(_filter).limit(10) // 最多顯示10條
    .sort({'_id': -1}) // 倒序
    .exec(function (err, doc) { // 回調
      if (err) {
        console.log(err)
      } else {
        res.json({code: 0, data: doc, count: count})
      }
    })
})

local.js

var mongoose = require('./db.js'),
  Schema = mongoose.Schema;

var LocalSchema = new Schema({
  key : { type: String },                    //變量
  en: {type: String},                        //英文
  cn: {type: String},                        //中文
  tn : { type: String}                       //繁體
});

module.exports = mongoose.model('Local',LocalSchema);

db.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  // yay!
});
module.exports = mongoose;

參考:https://smohan.net/blog/qz1etc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM