1. 程式人生 > >mongodb查詢語句及mongoose操作資料庫總結

mongodb查詢語句及mongoose操作資料庫總結

1.查詢某幾個欄位

    db.pers.find({age:15},{age:true,title:true});//查詢age=15的記錄的age和title欄位;

mongoose操作資料庫

var mongoose=require("mongoose");
var conn = mongoose.connect("mongodb://localhost/mytest");

var Schema = mongoose.Schema;
var ObjectId =  Schema.ObjectId;

var Person = new Schema({
    title:{type:String},
    age:{type:Number,min:5,max:20},
    meta:{
        likes:[String],
        birth:{type:String}
    }
});

var p = mongoose.model('per',Person);

var Blog = mongoose.model("per");


var blog1 = new Blog();
    blog1.title="Tom";
    blog1.age=17;
    blog1.meta={
        likes:"DOTA3",
        birth:"1989-06-19"
    };
//插入新紀錄
    blog1.save(function(err){
        if(err){
            console.log(err);
            console.log("save failed");
        }else{
            console.log("success!");
        }
    });
//查詢age=15的記錄
    Blog.find({age:15},function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//查詢age=15的記錄的age和title欄位;
    Blog.find({age:15},{age:true,title:true},function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//查詢所有記錄的age和title欄位;
    Blog.find({},{age:true,title:true},function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//修改age=15的記錄的title為"fuck2"
    var conditions = {age:15},
         update = {$set:{title:'fuck2'}};
    Blog.update(conditions,update,{},function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//鏈式寫法

//查詢title="JACK"的記錄

   Blog.find().where('title').equals('JACK').exec(function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//查詢age>10,從0開的3條記錄的age,title欄位
    Blog.find().where('age').gte(10).select('age title').skip(0).limit(3).exec(function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });
//查詢age=15,從0開的3條記錄的age,title欄位
    Blog.find({age:15}).select('age title').skip(0).limit(3).exec(function(err,docs){
        if(!err){
            console.log(docs);
        }else{
            console.log(err);
        }
    });