MongoDBに格納されているデータを、Mongooseで参照する処理の備忘録
フィールド名と値を全て取得する
ポイントはL14で、element変数(Mongooseのmodelクラス)のメンバ変数_docにドキュメントの値が全て格納されるので、for..inを使うことによって、不明なフィールド名も取得できる。ただし、MongoDB登録時のフィールドの順番は維持されない。
var mongoose = require("mongoose");
// DBは"hoge"
mongoose.connect('mongodb://localhost/hoge');
// フィールドが不明なので、スキーマは空
var sch = mongoose.Schema({});
// コレクションは"coll"
var mod = mongoose.model('coll', sch);
// とりあえず全て取得(select * from coll)
mod.find( {}, function(err, docs){
// ドキュメント件数分ループする
docs.forEach(function(element){
// オブジェクトのメンバ変数_docにMongDBのドキュメントの値が全て詰まっている
// for..inでドキュメントの全フィールドを取得する
for(var field in element._doc)
{
// ex.) field name = xxx, value = 1111
console.log( "field name = " + field + ", value = " + element._doc[field] );
}
},this);
});
特定のフィールド値を条件として検索する
// hoge=xxx
model.find({'hoge':'xxx'})
.exec(function(err,docs){
:
});
// xxxを含む(正規表現)
model.find({'hoge': new RegExp('xxx')})
.exec(function(err,docs){
:
});
// hoge=xxx and hoge2=zzz
model.find({'hoge':'xxx'})
.where({'hoge2':'zzz'})
.exec(function(err,docs){
:
});
// hoge=xxx and hoge2=yyy or hoge2=zzz
model.find({'hoge':'xxx'})
.or([{'hoge2':'yyy'},{'hoge2':'zzz'}])
.exec(function(err,docs){
:
});
// hoge=xxx and hoge2=yyy and hoge2=zzz
model.find({'hoge':'xxx'})
.and([{'hoge2':'yyy'},{'hoge2':'zzz'}])
.exec(function(err,docs){
:
});
範囲検索
// 0 <= x <= 10
model.find({})
.gte('x',0)
.lte('x',10)
.exec(function(err,docs){
:
});
// 0 < x < 10
model.find({})
.gt('x',0)
.lt('x',10)
.exec(function(err,docs){
:
});
ソート
// quantityの値で昇順ソート( 0,1,2... )
model.find({})
.sort('+quantity')
.exec(function(err,docs){
:
});
// quantityの値で降順ソート( 2,1,0... )
model.find({})
.sort('-quantity')
.exec(function(err,docs){
:
});
ページング
// quantityの値で昇順ソートし、1~5レコード取得
model.find({})
.sort('+quantity')
.skip(0)
.limit(5)
.exec(function(err,docs){
:
});
// quantityの値で昇順ソートし、6~10レコード取得
model.find({})
.sort('+quantity')
.skip(5)
.limit(5)
.exec(function(err,docs){
:
});