mogodb操作大全

本文介绍MongoDB中索引的创建、查询、更新及删除等基本操作,并提供了复合索引、唯一索引等高级用法,同时包含字段类型的更新、字段重命名及聚合查询等实用技巧。

<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">索引</span>

1、创建索引

OrgLoginCounter.ensureIndex({"orgId":1});

2、查看索引是否创建成功

OrgLoginCounter.getIndexes();


3、删除索引

OrgLoginCounter.dropIndex({"orgId":1})

4、创建复合索引

ccEnteryLogInfo.ensureIndex({"loginUser":1,"orgId":1});

5、创建唯一索引

ccEnteryLogInfo.ensureIndex({"userid":1},{"unique":true})


查询

1、多条件查询并排序(and查询)

db.getCollection('ccCollection').find({orgId:"aa", loginTime: { "$gte": "2016-07-12 00:00:00" ,"$lte": "2016-07-12 23:59:59"}} ).sort({'loginTime':-1}).limit(50)

2、聚合查询,有条件的分组查询带排序和Limit

db.getCollection('ccCheckLoginLogs').aggregate([  
    {$match: { "loginDate" :{"$lte": "2016-10-26 13:46:00"},username:"cloudcc@app1.com"}},  
    {$group: {_id: {"username": "$username","loginResult": "$loginResult","loginDate": "$loginDate"}, "count": {$sum: 1}}},  
    {$sort: {_id: -1}},  
    {$limit: 6}  
])  



更新

1、更新表字段数据类型

db.getCollection('ccCollection').find( { loginTime : { $exists : true } } ).forEach( function (x) { 
  x.loginTime = new String(x.loginTime);  //将字段类型转换为String
  //x.user_id = new NumberInt(x.user_id); //将字段类型转换为Int
  db.getCollection('ccCollection').save(x); 
});

2、更新表字段名称(表字段重命名)

db.getCollection('ccCollection').update({}, {$rename : {"orgID" : "orgId"}}, false, true);

3、更新字段值

db.getCollection('ccCollection').update({},{$set:{todayLoginCount:"0",thisWeekCount:"0",thisMonthCount:"0"}}, false, true)

删除

1、查询某个字段是否存在,并删除这个字段

db.course.find( { "lectures.lectures_count": { $exists: true } } )
db.course.update({},{$unset:{"lectures.lectures_count":""}},{multi:true})







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值