LoginSignup
6
10

More than 5 years have passed since last update.

mongooseで〜以外の指定(not equal | !=)

Last updated at Posted at 2014-02-26

node.jsでMongoDBを扱うときに利用するmongooseで,「〜以外」を検索するやり方です.

「〜以外」を検索

index.js
//例: nameフィールドがn0bisuke以外を検索
var query = {name: {'$ne':"n0bisuke"}};
    User.find(query,{},{sort:{point: -1}}, function(err, all_data){
        if(err){
            console.log(err);
        }
    });

参考:node.js - nodejs - mongodb - how to find all where a != b? - Stack Overflow

複数の条件指定

ANDやORも使えるっぽいので使ってみました.[]で複数指定するみたいです.

index2.js
//例: 「複数の〜以外」を条件に
var query = {'$and':[
                {name:{'$ne':"n0bisuke"}}, //nameフィールドがn0bisuke以外
                {name:{'$ne':"otukutun"}}, //nameフィールドがotukutun以外
                {email:{'$ne':"hoge@example.com"}}//emailフィールドがhoge@example.com以外
            ]};
User.find(query,{},{sort:{point: -1}}, function(err, all_data){
    if(err){
        console.log(err);
    }
});

参考:mongodb - Mongoose's find method with $or condition does not work properly - Stack Overflow

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10