常用mongo语句

1、根据objectId类型字段checkId并根据_id倒排序查询

db.xxx.find({"checkId" : ObjectId("5f1ff24a82d5dd3d54b4e82d")}).sort({_id:-1}).limit(20);

db.xxx.find({addTime:{"$gt":1596279600, "$lte":1596366000},typeId:1,isRegister:1}).limit(20);

2、查询数量

db.xxx.find().count();

db.xxx.find({addTime:{"$gt":1596279600, "$lte":1596366000},typeId:1,isRegister:1}).count();

3、新增字段

update命令

update命令格式:

db.collection.update(criteria,objNew,upsert,multi)

参数说明:

criteria:查询条件

objNew:update对象和一些更新操作符

upsert:如果不存在update的记录,是否插入objNew这个新的文档,true为插入,默认为false,不插入。

multi:默认是false,只更新找到的第一条记录。如果为true,把按条件查询出来的记录全部更新。

 

4、添加索引

db.xxx.createIndex({strategy:1},{name:"IX_strategy"});

 

 

5、批量更新

方法一:db.xxx.update( { "risk_result" : 10} , { $set : { "strategy" : "30000"} },false,true );

方法二:

db.getCollection('xxx').find({"risk_result":10}).forEach(
function(item){
db.getCollection('xxx').update({"_id":item._id},{$set:{"strategy": 30000}})
}
);

6、mongo只查询指定字段

db.xxxx.find({},{"_id":false,"userId":true,"userName":true}).limit(20);

 

 注意:mongo的in很影响查询性能:db.xxxxx.find("result" : { "$in" : [2] })

mongo复合索引的使用原则:

  • 最左前缀原则 

  • 查询条件顺序无关原则

  • 多多非益善

  • 查询优化器

posted @ 2020-12-01 18:39  乌瑟尔  阅读(264)  评论(0编辑  收藏  举报