MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全
--http://www.jb51.net/article/28694.htm


MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的

他支持的数据结构非常松散,是类似json的jsonb格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
它的特点是高性能、易部署、易使用,存储数据非常方便。



2. 熟悉MongoDB的数据操作语句,类sql

数据库操作语法
mongo --path
db.AddUser(username,password) 添加用户
db.auth(usrename,password) 设置数据库连接验证
db.cloneDataBase(fromhost) 从目标服务器克隆一个数据库
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb,todb,fromhost) 复制数据库fromdb---源数据库名称,todb---目标数据库名称,fromhost---源数据库服务器地址
db.createCollection(name,{size:3333,capped:true,max:88888}) 创建一个数据集,相当于一个表 ,size是字节数  max是最大文档数,固定集合,size参数和max参数才起作用,不是固定集合这两个参数设置了也白设
db.currentOp() 取消当前库的当前操作
db.dropDataBase() 删除当前数据库
db.eval(func,args) run code server-side
db.getCollection(cname) 取得一个数据集合,同用法:db['cname'] or db.cname
db.getCollenctionNames() 取得所有数据集合的名称列表
db.getLastError() 返回最后一个错误的提示消息
db.getLastErrorObj() 返回最后一个错误的对象
db.getMongo() 取得当前服务器的连接对象get the server connection object
db.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr of a replica pair
db.getName() 返回当操作数据库的名称
db.getPrevError() 返回上一个错误对象
db.getProfilingLevel() ?什么等级
db.getReplicationInfo() ?什么信息
db.getSisterDB(name) get the db  获得数据库db.getSiblingDB("aa").getCollection('bb').find()

db.getSiblingDB(name) get the db  获得数据库
db.killOp() 停止(杀死)在当前库的当前操作
db.printCollectionStats() 返回当前库的数据集状态
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus() 返回当前数据库是否为共享数据库
db.removeUser(username) 删除用户
db.repairDatabase() 修复当前数据库
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level) 0=off,1=slow,2=all
db.shutdownServer() 关闭当前服务程序
db.version() 返回当前程序的版本信息

数据集(表)操作语法
db.linlin.find({id:10}) 返回linlin数据集ID=10的数据集
db.linlin.find({id:10}).count() 返回linlin数据集ID=10的数据总数
db.linlin.find({id:10}).limit(2) 返回linlin数据集ID=10的数据集从第二条开始的数据集
db.linlin.find({id:10}).skip(8) 返回linlin数据集ID=10的数据集从0到第八条的数据集
db.linlin.find({id:10}).limit(2).skip(8) 返回linlin数据集ID=1=的数据集从第二条到第八条的数据
db.linlin.find({id:10}).sort() 返回linlin数据集ID=10的排序数据集
db.linlin.findOne([query]) 返回符合条件的一条数据
db.linlin.getDB() 返回此数据集所属的数据库名称
db.linlin.getIndexes() 返回些数据集的索引信息
db.linlin.group({key:...,initial:...,reduce:...[,cond:...]})
db.linlin.mapReduce(mayFunction,reduceFunction,<optional params>)
db.linlin.remove(query) 在数据集中删除一条数据
db.linlin.renameCollection(newName) 重命名集合名称
db.linlin.save(obj) 往数据集中插入一条数据
db.linlin.stats() 返回此数据集的状态
db.linlin.storageSize() 返回此数据集的存储大小
db.linlin.totalIndexSize() 返回此数据集的索引文件大小
db.linlin.totalSize() 返回些数据集的总大小
db.linlin.update(query,object[,upsert_bool]) 在此数据集中更新一条数据
db.linlin.validate() 验证此数据集 ,只有一个选项full,检查集合数据
db.linlin.getShardVersion() 返回数据集共享版本号

db.linlin.find({'name':'foobar'}) select * from linlin where name='foobar'
db.linlin.find() select * from linlin
db.linlin.find({'ID':10}).count() select count(*) from linlin where ID=10
db.linlin.find().skip(10).limit(20) 从查询结果的第十条开始读20条数据 select * from linlin limit 10,20 ----------mysql
db.linlin.find({'ID':{$in:[25,35,45]}}) select * from linlin where ID in (25,35,45)
db.linlin.find().sort({'ID':-1}) select * from linlin order by ID desc
db.linlin.distinct('name',{'ID':{$lt:20}}) select distinct(name) from linlin where ID<20

db.linlin.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}})
select name,sum(marks) from linlin group by name
db.linlin.find('this.ID<20',{name:1}) select name from linlin where ID<20

db.linlin.insert({'name':'foobar','age':25}) insert into linlin ('name','age') values('foobar',25)
db.linlin.insert({'name':'foobar','age':25,'email':'cclove2@163.com'})

db.linlin.remove({}) delete * from linlin
db.linlin.remove({'age':20}) delete linlin where age=20
db.linlin.remove({'age':{$lt:20}}) delete linlin where age<20
db.linlin.remove({'age':{$lte:20}}) delete linlin where age<=20
db.linlin.remove({'age':{$gt:20}}) delete linlin where age>20
db.linlin.remove({'age':{$gte:20}}) delete linlin where age>=20
db.linlin.remove({'age':{$ne:20}}) delete linlin where age!=20

db.linlin.update({'name':'foobar'},{$set:{'age':36}}) update linlin set age=36 where name='foobar'
db.linlin.update({'name':'foobar'},{$inc:{'age':3}}) update linlin set age=age+3 where name='foobar'

官方提供的操作语句对照表:

上行:SQL 操作语句
下行:Mongo 操作语句
CREATE TABLE USERS (a Number, b Number)
db.createCollection("mycoll")

INSERT INTO USERS VALUES(1,1)
db.users.insert({a:1,b:1})

SELECT a,b FROM users
db.users.find({}, {a:1,b:1})

SELECT * FROM users
db.users.find()

SELECT * FROM users WHERE age=33
db.users.find({age:33})

SELECT a,b FROM users WHERE age=33
db.users.find({age:33}, {a:1,b:1})

SELECT * FROM users WHERE age=33 ORDER BY name
db.users.find({age:33}).sort({name:1})

SELECT * FROM users WHERE age>33
db.users.find({'age':{$gt:33}})})

SELECT * FROM users WHERE age<33
db.users.find({'age':{$lt:33}})})

SELECT * FROM users WHERE name LIKE "%Joe%"
db.users.find({name:/Joe/})

SELECT * FROM users WHERE name LIKE "Joe%"
db.users.find({name:/^Joe/})

SELECT * FROM users WHERE age>33 AND age<=40
db.users.find({'age':{$gt:33,$lte:40}})})

SELECT * FROM users ORDER BY name DESC
db.users.find().sort({name:-1})

SELECT * FROM users WHERE a=1 and b='q'
db.users.find({a:1,b:'q'})

SELECT * FROM users LIMIT 10 SKIP 20
db.users.find().limit(10).skip(20)

SELECT * FROM users WHERE a=1 or b=2
db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } )

SELECT * FROM users LIMIT 1
db.users.findOne()

SELECT DISTINCT last_name FROM users
db.users.distinct('last_name')

SELECT COUNT(*y) FROM users
db.users.count()

SELECT COUNT(*y) FROM users where AGE > 30
db.users.find({age: {'$gt': 30}}).count()

SELECT COUNT(AGE) from users ,表中的数据行存在age这个字段的,就进行统计
db.users.find({age: {'$exists': true}}).count()

CREATE INDEX myindexname ON users(name)
db.users.ensureIndex({name:1})

CREATE INDEX myindexname ON users(name,ts DESC)
db.users.ensureIndex({name:1,ts:-1})

EXPLAIN SELECT * FROM users WHERE z=3
db.users.find({z:3}).explain()

UPDATE users SET a=1 WHERE b='q'
db.users.update({b:'q'}, {$set:{a:1}}, false, true)

UPDATE users SET a=a+2 WHERE b='q'
db.users.update({b:'q'}, {$inc:{a:2}}, false, true)

DELETE FROM users WHERE z="abc"
db.users.remove({z:'abc'});

 

 


解决表关联

内嵌模型

一个用户发布了多篇博客,一个用户表,一个博客文章表,两个表做关联,用户文档里面嵌入文章子文档

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全
引用模型

通过_id用户id,contact文档和access文档引用user文档的用户id

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

 

orm中的四种关系

一对一 ,主键相同

一对多,外键引用

多对多,中间表

继承关系,多表/冗余字段

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

 

内嵌就是组合,引用就是聚合

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

 f

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

f

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

f

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全

 


 

3.3.4.月活跃 月注册 月付费 月活跃度 Arpu.远航麻将

MongoDB mongo shell javascript api语法使用小结  数据库操作语法大全
var begin_date=new Date('2019/01/01 00:00:00');
var end_date=new Date('2019/04/01 00:00:00');

var current_date=begin_date;

var month_active=0;
var month_reg=0;
var month_payaccounts=0;
var month_totaccounts=0;
var month_activescale=0.0;
var month_arpu=0.0;
var month_payamount=0;

var month_date_array=[];
var month_active_array=[];
var month_reg_array=[];
var month_payaccounts_array=[];
var month_totaccounts_array=[];
var month_activescale_array=[];
var month_arpu_array=[];
var month_payamount_array=[];

while(current_date<end_date){
    var month_begin_date = current_date;
    month_begin_date.setDate(1);
    var month_end_date = new Date(month_begin_date)
    month_end_date.setMonth(month_end_date.getMonth()+1);
    month_end_date.setDate(0);

    if(month_begin_date < begin_date){
        month_begin_date = begin_date;
    }
    
    if(month_end_date>end_date){
        month_end_date = end_date;
    }

    var month_begin_time=month_begin_date.getTime()/1000;
    var month_end_time=month_end_date.getTime()/1000+86399;

    month_active=0;
    month_reg=0;
    month_payaccounts=0;
    month_totaccounts=0;
    month_activescale=0.0;
    month_arpu=0.0;
    month_payamount=0;

    month_active = db.getSiblingDB("log").getCollection('login').distinct("user_id",{"time":{$gte:month_begin_time,$lte:month_end_time}}).length;
    month_payaccounts = db.getSiblingDB("log").getCollection('order_info').distinct("user_id",{"pay_time":{$gte:month_begin_time,$lte:month_end_time},"charge_up_status":1}).length;
    db.getSiblingDB("log").getCollection('order_info').find({"pay_time":{$gte:month_begin_time,$lte:month_end_time},"charge_up_status":1}).forEach(
        function(coll){
            if(typeof(coll.order_amount)!= "undefined")
            {
                month_payamount=month_payamount+parseFloat(coll.order_amount);
            }
        }
    )

    month_reg = db.getSiblingDB("user").getCollection('signup_info').distinct("user_id",{"time":{$gte:month_begin_time,$lte:month_end_time}}).length;
    month_totaccounts = db.getSiblingDB("user").getCollection('signup_info').distinct("user_id").length;

    month_activescale=(month_active/month_totaccounts).toFixed(4)

    if(month_active>0){
        month_arpu=(month_payamount/month_active).toFixed(4);
    }

    var y = current_date.getFullYear();
    var m = current_date.getMonth() + 1;

    month_date_array.push(y+"-"+m);
    month_active_array.push(month_active);
    month_reg_array.push(month_reg);
    month_payaccounts_array.push(month_payaccounts);
    month_totaccounts_array.push(month_totaccounts);
    month_activescale_array.push(month_activescale);
    month_arpu_array.push(month_arpu);
    month_payamount_array.push(month_payamount);
    
    current_date.setMonth(current_date.getMonth()+1);
}

for (var i=0;i<month_active_array.length;i++){
    print(month_date_array[i]+"    "+month_active_array[i]+"    "+month_reg_array[i]+"    "+month_payaccounts_array[i]+"    "+month_totaccounts_array[i]+"    "+month_activescale_array[i]+"    "+month_arpu_array[i]+"    "+month_payamount_array[i]);
}
View Code

相关文章:

  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
  • 2021-08-10
  • 2021-11-28
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-05-24
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案