###主从切换,指定时间30S后切换
rs.stepDown(30)
###查看副版本状态
rs.status()
###创建集合
db.createCollection('student')
###集合列表
show collections
###删除集合
db.student.drop()
###插入一条数据
db.test1201.insertOne({test:1201})
###插入多条数据
db.test1201.insertMany([{'test':1202,'test2':1203},{'test3':1201,'test4':1203}])
###查看集合文档内容
rs.collecttest.find()
###查看集合详情
db.student.stats()
###查看索引
db.getCollection('xx').getIndexes()
###创建索引
代表升序,-1代表降序,name 指定索引名
db.getCollection('xx').createIndex( {"title": 1}, {"name":"idx_xxx"} );
###创建复合索引
db.getCollection('xx').createIndex( {"title": 1, "created_at": -1} );
###内嵌字段创建索引
db.集合名.createIndex( {"字段名.内嵌字段名":1}, {"name":'idx_字段名_内嵌字段名'} )
###删除索引
db.getCollection('xx').dropIndex("idx_xxx");
###查询前三条
db.book.find().limit(3);
###只显示某个字段
db.T_ServiceTypeTemplate.find({},{"createTime": 1})
###多条件查询
db.集合名称.find( { $or : [ { 字段1 : 值1 }, { 字段2 : 值2 } ... ] } )
###修改字段内容
db.T_U.update({"wid":"102"},{$set:{"nId":"5170b3ede4b035e16493be37"}},{multi:true})
###加条件更改
db.T_U.update({"wid" : "101","jobTitle" : "职员"},{$set:{"jobTitle" : ""}},{multi:true})
###导出-q 过滤条件
./mongoexport -h xxx.xxx.xxx.xxx --port=27017 --username=xxx --password='xxxxxx' --authenticationDatabase=admin -d dbbame -c collection -q '{"aId" : "500000009", sendTime: {$lt: ISODate("2022-10-21T00:00:00Z"),$gte: ISODate("2021-01-01T22:00:00Z")}}' -f _id,sourceId --type csv -o T_D1021.csv
###导入
./mongoimport -h xxx.xxx.xxx.xxx --port 27017 -u xxx -p 'xxxxxxxxxxx' --authenticationDatabase=dbbame -d dbbame -c collection T_P0310bak.json
###shell执行mongo命令
####查询库
echo -e "show dbs" | /path/to/mongo --quiet --host=xx.xx.xx.xx --port=27017 -u username -p 'XXX' --authenticationDatabase=admin
####查询表
echo -e "use testDB;\n db.testColl.findOne()" | /path/to/mongo --quiet --host=xx.xx.xx.xx --port=27017 -u username -p 'XXX' --authenticationDatabase=admin
####清空表
echo -e "use testDB;\n db.testColl.remove({})" | /path/to/mongo --quiet --host=xx.xx.xx.xx --port=27017 -u username -p 'XXX' --authenticationDatabase=admin
###shell脚本中使用
#!/bin/bash
db=xxx
tables='
xxx
'
for table in ${tables[@]}
do
echo $table
echo -e "use $db;\n db.${table}.remove({})" | /path/to/mongo --quiet --host=xx.xx.xx.xx --port=27027 -u username -p 'XXX' --authenticationDatabase=admin
done
###模糊查询
假设我们要查询一个名为“people”的集合中,所有名字中包含“Tom”的文档,可以使用以下代码:
db.people.find({name: {$regex: 'Tom'}})
其中,$regex表示正则表达式,'Tom'表示要查询的字符串。
如果要查询名字中包含“Tom”的文档,且不区分大小写,可以使用以下代码:
db.people.find({name: {$regex: 'Tom', $options: 'i'}})
其中,$options表示正则表达式的选项,'i'表示不区分大小写。
如果要查询名字中包含“Tom”或“Jerry”的文档,可以使用以下代码:
db.people.find({name: {$regex: 'Tom|Jerry'}})
其中,'|'表示或的关系。
如果要查询名字中以“Tom”开头的文档,可以使用以下代码:
db.people.find({name: {$regex: '^Tom'}})
其中,'^'表示以某个字符串开头。
如果要查询名字中以“Tom”结尾的文档,可以使用以下代码:
db.people.find({name: {$regex: 'Tom$'}})
其中,'$'表示以某个字符串结尾。