搜档网
当前位置:搜档网 › Mongodb笔记

Mongodb笔记

Mongoose:
var express = require('express');
var router = express.Router();
var mongoose = require("mongoose");
连接数据库:
mongoose.connect("mongodb://localhost:27017/test", {
server: {
keepAlive: true
}
});
编写文档:(类似于hibernate的表实体类Entity)
var userSchema = mongoose.Schema({
id: String,
username: String,
password: String,
age: Number,
isValid: Boolean,
createTime: Date
});
自定义方法:
userSchema.methods.getFullName = function () {
return "姓名:" + https://www.sodocs.net/doc/e59579843.html,ername + ",年龄:" + this.age;
};
创建表(表明为modelName+"s"):
var UserModel = mongoose.model("user", userSchema); //创建model,model的名字对应于数据库中的name+"s"

增删查改的方法:
新增:save(function(err,data){}) //如果报错返回err,如果成功返回新增的数据
修改:update( { 条件 } , { 修改的实体内容 } , function(err,result){}) //如果报错返回err,如果成功返回成功状态
删除:remove( { 条件 } , function(err,result){}) //如果报错返回err,如果成功返回成功状态
查询:find( [ { 条件 } ] ,function(err,data){}) //如果报错返回err,如果成功查询出来的数据
查询单条: findOne( { 条件 } , function(err,data){}) //如果报错返回err,如果成功查询出来的数据
查询条数:count( { 条件 } , function(err,data){}) //如果报错返回err,如果成功返回条数
不重复查询:distinct( 字段 , function(err,data){}) //字段参数必须要填
条件列举:$gt,$gte,$lt,$lte,$ne,$or,$in,$nin
UserModel.find({
"age" : "22",
"subdate" : { $lt : 20160211 , $gt : 20110211 },
"name" : { $in [ 'a','b' ] }
}).select('name.first,https://www.sodocs.net/doc/e59579843.html,st').limit(5).sort({age:-1}).then(function(data){
console.log(data);
},function(err){
console.log(err);
})
--查询UserModel所对应的Modelname表下
age = 22 and subdate >20110211 and subdate < 20160211 and name in ('a','b')的name.first,https://www.sodocs.net/doc/e59579843.html,st字段并根据age进行降序,只显示 5条数据
Mongoose增删改查的一个类:
var express = require('express');
var router = express.Router();
var mongoose = require("mongoose");
//连接mongodb
mongoose.connect("mongodb://localhost:27017/test", {
server: {
keepAlive: true
}
});
//文档
var userSchema = mongoose.Schema({
id: String,
username: String,
password: String,
age: Number,
isValid: Boolean,
createTime: Date
});
userSchema.methods.getFullName = function () {

return "姓名:" + https://www.sodocs.net/doc/e59579843.html,ername + ",年龄:" + this.age;
};
var UserModel = mongoose.model("user", userSchema); //创建model,model的名字对应于数据库中的name+"s"
/**
* 新增
*/
var UserEntity = new UserModel({
"username": "与离",
"password": "12346",
"age": 16,
"isValid": true,
"createTime": Date.now()
});
UserEntity.save(function(err,user){
if(err){
console.log("保存失败:"+err);
}else{
console.log("保存成功:"+user);
}
});
/**
* 修改
*
* 在修改中,mongodb提供了2种可以只修改单个字段的方法:$inc 和 $set
* UserModel.update({ "name" : "点点" },{ $inc: { "age":30} }) $inc会在原有的字段值的基础上增加更新的值,此时age为52
* UserModel.update({ "name" : "点点" },{ $set : { "age":30} }) $inc会将该字段直接修改为更新的值,此时age为30
*
* UserModel.update({ "name" : "点点" },{ $inc: { "age":15} } , true)
* 在第三个条件上加一个true,意思为,如果找不到修改的数据,则新增一条 ,类似于 hibernate 的 saveOrUpdate
*
* 在mongodb中如果匹配多条,默认的情况下只更新第一条,
* 那么如果我们有需求必须批量更新,在update的第四个参数中设为tr ue即可。
*/
UserModel.update({"password":"2106531"},{
"username": "点点",
"password": "2106531",
"age": 22,
"isValid": true,
"createTime": Date.now()
},function(err,result){
if(err){
console.log("更新失败:"+err);
}else{
console.log("更新成功:");
for(var key in result){
console.log(key+"..."+result[key]);
}
}
});
/**
* 删除
*/
UserModel.remove({"password":"2106531"},function(err,result){
if(err){
console.log("删除失败:"+err);
}else{
console.log("删除成功");
}
});
/**
* 查询
*/
UserModel.find(function(err,data){
if(err){
console.log("查询失败:"+err);
}else{
//console.log("查询成功:"+data);
for(var i=0;i var user = data[i];
console.log(https://www.sodocs.net/doc/e59579843.html,ername+"..."+user.age);
}
}
});
/**
* 查询条数
*/
UserModel.count(function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
/**
* 不重复查询 根据age不重复查询,查询出来的数据只显示age
*/
UserModel.distinct("age",function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
/* GET users listing. */
r

outer.get('/', function (req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
------------------------------------------------------------------------
/**
* 分组,(还不知道在node.js中怎么实现,mongodb中的代码如下:)
* key: 这个就是分组的key,我们这里是对年龄分组。
* initial: 每组都分享一个”初始化函数“,比如这个的age=20的value的list分享一个initial函数,age=22同样也分享一个initial函数。
* $reduce: 这个函数的第一个参数是当前的文档对象,
* 第二个参数是上一次function操作的累计对象,第一次为initial中的{”perosn“:[]}。有多少个文档, $reduce就会调用多少次。
*/

https://www.sodocs.net/doc/e59579843.html,ers.group({
"key":{"age":true},
"initial":{user:[]},
"$reduce":function(cur,prev){
https://www.sodocs.net/doc/e59579843.html,er.push(https://www.sodocs.net/doc/e59579843.html,ername);
}
})
-- 查询出的结果为:
[ { "age":16 , "user" : [ "aa" , "bb" ] } ] // aa ,bb 为 age = 16 的 username
/**
* 如果要加上条件和统计条数,则需要增加condition和finalize的options
*/
https://www.sodocs.net/doc/e59579843.html,ers.group({
"key":{"age":true},
"initial":{user:[]},
"$reduce":function(cur,prev){
https://www.sodocs.net/doc/e59579843.html,er.push(cur);
},
"condition" : { "age": { $gte : 16 } }, //大于等于16
"finalize" : function(out){
out.count = https://www.sodocs.net/doc/e59579843.html,er.length;
}
})
-- 查询出的结果为:
[
{
"age" : 16,
"user" : [
{
"_id" : ObjectId("573142e0747edb0019e5f0e2"),
"username" : "与离",
"password" : "12346",
"age" : 16,
"isValid" : true,
"createTime" : ISODate("2016-05-10T02:09:36.504Z"),
"__v" : 0
},
{
"_id" : ObjectId("57314def5d9c377019ba9d28"),
"username" : "点点",
"password" : "12346",
"age" : 16,
"isValid" : true,
"createTime" : ISODate("2016-05-10T02:56:47.626Z"),
"__v" : 0
}
],
"count" : 2
},
{
"age" : 29,
"user" : [
{
"_id" : ObjectId("5739546623e820e014959f5d"),
"username" : "笑笑",
"password" : "12346",
"age" : 29,
"isValid" : true,

"createTime" : ISODate("2016-05-16T05:02:30.237Z"),
"__v" : 0
}
],
"count" : 1
}
]
建立索引:
https://www.sodocs.net/doc/e59579843.html,ers.ensureIndex({"name":1}) //在name字段上建立索引,1代表升序,-1代表降序
唯一索引:
https://www.sodocs.net/doc/e59579843.html,ers.ensureIndex({"name":1},{"unique":true})
删除索引:
https://www.sodocs.net/doc/e59579843.html,ers.dropIndexes("name_1");

相关主题