MongoDB日常脚本

39 阅读2分钟

1、查询索引列表

查看 t_test_log1 的所有索引列表。

db.t_test_log1.getIndexes();

2、排序查询并返回指定字段

查看 t_test_log1 的所有记录,并按 createTime 倒序,且只返回 _idbizNocreateTime字段。

db.t_test_log1.find({},{_id:1,bizNo:1,createTime:1}).sort({ createTime: -1 });

3、创建唯一索引

db.t_test_log1.createIndex(
  { bizNo: 1, bizType: 1, bizCode: 1, deleteTime: 1 },
  { unique: true, background: true }
);

注意:创建索引时可以通过设置 background 选项为 true 来让索引在后台创建。这样可以避免在创建索引的过程中阻塞数据库的其他操作。

4、创建普通索引

db.t_test_log1.createIndex(
  { bizType: 1, bizCode: 1, useTime: -1 },
  { background: true }
);

创建索引时可以通过设置 background 选项为 true 来让索引在后台创建。这样可以避免在创建索引的过程中阻塞数据库的其他操作。

5、重命名集合名称

重命名 t_test_logt_test_log1

db.adminCommand({
  renameCollection: "test_db.t_test_log",
  to: "test_db.t_test_log1"
});

6、条件修改某个字段值

修改 bizNo23874832483 的文档的 bizType 值为 1,且只修改符合条件的第一条数据。

db.t_test_log.update({'bizNo':'23874832483'},{$set:{'bizType': '1'}})

如果想把所有符合条件的文档数据都修改了,则加上:{multi:true}

db.t_test_log.update({'bizNo':'23874832483'},{$set:{'bizType': '1'}},{multi:true})

查询

简单查询

select * from  spu where  spu_name="test0123"

db.spu.find({ spu_name:"test0123" })

and

select * from  spu where  spu_name="test0123" and  type=3

db.spu.find({spu_name:"test0123", type:"3" });

like

select * from  user where  username like "%test0123%"

db.user.find({username:/test0123/});

大于等于、小于等于

//大于、大于等于、小于、小于等于 $lt, $lte, $gt, $gte
select * from  user where  age>=10 and age<=20

db.user.find({ age:{$gte:10, $lte:20} });

等于null

select * from  user where  address is null

db.user.find({ address: null });

不为null

select * from  user where  address is not null

db.user.find({ address: {$ne:null} });

不为null 且不为""

select * from  user where  address is not null and address !=''

db.user.find({ address: {$nin:[null,"" ]} });

in/not in

db.activity.find({ event: {$in:[50,60,70]} });
db.activity.find({ event: {$nin:[50,60,70]} });

count

db.activity.find().count();
db.activity.find({ event: {$in:[50,60,70]} }).count();

distinct

db.activity.distinct("user_name");

sort

db.getCollection("activity").find({type:10}).sort({createTime:1});

时间段

查询某个时间段的数据

db.activity.find({createTime:{$gte:ISODate('2020-03-01T00:00:00.000Z'), $lte:ISODate( '2020-03-11T00:00:00.000Z' )}});