mongodb常用命令
增:
db.php27.insert({“name”:”赵六”,”age”:26,”gender”:”nan”});
db.php27.insert([
{“name”:”lisi”,”age”:20},
{“name”:”zhaohua”,”age”:30},
{“name”:”hanmeimei”,”age”:16},
{“name”:”liuneng”,”age”:18},
]);
改: db.php27.update({“name”:”lisi”},{“age”:30});//将name字段为lisi的文档给删了,只保留age字段,改为30,
db.php27.update({“name”:”lisi”},{$set:{“age”:30}});
//将name字段为lisi的文档给保留,只更改age字段,改为30,
db.php27.update({“name”:”lisi”},{$rename:{“age”:”age1″}});
查:db.php27.find();//查所有
db.php27.findOne();
db.php27.find().limit(5);
db.php27.find().count();
db.php27.find({“name”:”lisi”}).pretty();//查name是lisi的数据,以优雅的方式显示
//条件查询
db.php27.find({“age”:{$in:[21,18]}});//查age是21和18的数据
db.php27.find({“age”:{$nin:[21,18]}});//查age不是21和18的数据
db.php27.find({“gender”:{$exist:1}});
db.php27.find({“name”:”lisi”,”gender”:{$exists:1}});//查name是lisi ,且性别字段是存在的
db.php27.find({“gender”:{$exists:1},”name”:”lisi”}});//效果同上
db.php27.find({“name”:/^\w+$/});//支持正则表达式
db.php27.find({“name”:/诺基亚.*/});
db.php27.find({“$where”:”this._id != 3 && this._id != 8″});//不建议使用,效率慢
游标:
var res = db.php27.find();//查询的结果就是游标(其实就是资源)
while(res.hasNext()){ //判断游标是否已经读取到了尽头,只要有游标就循环
printjson(res.next());//取出游标的下一个单元.以json格式打印
}
var shuju = db.php27.find();shuju.forEach(function(obj){
printson(obj);
});
mapreduce(分类统计):分布式大规模数据(>1T)并发计算.只需要告知按谁分类,统计什么就可以了.因为内置算法是hadroop(哈droop)<==>自动饺子机:自动和面,搅馅,包饺子
应用:1:求学生的平均年龄.
db.stu.insert([
{“name”:”zhangshan”,”age”:20,”class”:26},
{“name”:”lisi”,”age”:19,”class”:26},
{“name”:”wangwu”,”age”:20,”class”:27},
{“name”:”liuli”,”age”:30,”class”:27},
{“name”:”zhaoliu”,”age”:20,”class”:26},
]);
var map = function(){
emit(this.class,this.age);
};var reduce = function(key,value){
return Array.avg(value);
};db.stu.mapReduce(map,reduce,{out:’res’});
//将dz.csv数据导入mogodb自建的名叫php数据库
./bin/mongoimport –file=/usr/local/mongodb/dz.csv –type=csv –headerline -d php -c dizhen;
var map = function(){
var wd = parseInt(this.wd / 5)*5;
var jd = parseInt(this.jd / 5)*5;
var area = wd + “:” + jd;
emit(area,1);//emit分类:按照wd:jd分类,有值则给1
};var reduce = function(key , value){
return Array.sum(value);
};db.dizhen.mapReduce(map,reduce,{out:”dzres”});
热力图展示
var cursor = db.dzres.find();
var row;
cursor.forEach(function(obj){
row = obj._id.split(“:”);
db.reli.insert({“lng”:parseFloat(row[1])+2.5,”lat”:parseFloat(row[0])+2.5,”count”:obj.value});
});
./bin/mongoexport –pretty -d php -c reli –out=./reli.json