mongo常用查询更新删除语句

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ywlmsm1224811/article/details/91491651

mongo常用查询、更新、删除等语句


注意:文中的所有 collection 代表 mongo 表名称

查询:

1、基础条件查询
db.collection.find({“type” : “test”);

2、区间查询

db.collection.find({"type":"test","addTime":{$lte:ISODate("2019-06-11T59:59:00.492+08:00"),$gte:ISODate("2019-06-12T00:00:00.492+08:00")}});

3、数组列表in查询
db.collection.find({“type”:“test”,“ids”:{$in: [1,2,3]}});

4、分页排序查询,倒序(-1),正序(1)
db.collection.find({“type”:“test”}).sort({“addTime”:-1}).skip(0).limit(2);

5、分组查询,统计type类型的age总和

db.collection.aggregate([{$group:{_id:"$type",total:{$sum:"$age"}}}]);

6、带条件的分组查询,统计name非空,type类型的age总和

db.collection.aggregate([{$match:{"name":{$ne:null}}},{$group:{_id:"$type",total:{$sum:"$age"}}}]);

更新:

1、更新字段,其中属性1是条件,2是更新field,3是如果记录不存在,是否插入记录,默认是false,4是是否更新查找到的全部记录,默认是false(只更新找到的第一条数据)

db.collection.update({"_id": ObjectId('123456')},{$set:{"type":"test"}},false,true);

2、增加索引,倒序(-1),正序(1)

db.collection.ensureIndex({type:1})

删除:

1、整个表删除

db.collection.drop()

2、删除某些条件的数据,删除type类型是test的数据

db.collection.remove({"type" : "test"})

猜你喜欢

转载自blog.csdn.net/ywlmsm1224811/article/details/91491651