[ linux-009 ] Mongo常用命令

151 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第26天,点击查看活动详情

本节主要介绍,常用的mongo数据库操作相关指令

认证命令

认证命令用于使用账号密码登录mongo,并使用admin数据库进行验证

mongo use admin db.auth("username","password") use assets

db.adminCommand({getParameter:"*"})

show dbs;

show databases;

查找

mongodb中常用的查找语句使用方法示例

db.getCollection('linux_host').find({})

db.getCollection('linux_host').find({"displayIp" : "192.168.42.131"})

db.getCollection('win_host').find({"displayIp" : "172.16.2.144"})

db.getCollection('linux_host').find({"root" : false})

db.linux_host.count();

模糊查询

在mongodb中进行关键字模糊匹配

db.linux_host.find({rootDir: /test/})

插入记录

在mongo中插入一条多字段的记录

db.warn_info.insert({

    "dstIp": "172.16.2.247",

    "dstGroup": 8,

    "dstPort": 22,

    "dstType": 1,

    "pname": "sshd"

})

更新字段值,所有记录默认赋值

更新mongo中所有或者指定的记录

db.getCollection('linux_host').update({},{$set:{root:false}},{multi:true})

db.hq_node.find({})

db.hq_node.update({},{$set:{ip:'172.16.17.193',port:9091}})

db.hosts.updateMany({}, {$set: {'available': 'yes'}})

更新一条记录,添加字段并赋值

在mongo添加新的字段,并且赋予默认值

db.linux_host.updateOne({_id:"6040a49c209d75d3"}, {$set: {

    "root": "false",

    "runAccount": "test"

}})

将mongo中的字段进行重命名

参数说明:

criteria:查询条件

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

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

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

记录删除

删除mongo中的的记录

db.token.remove({});

字段删除

删除mongo中的的字段

db.linux_host.update({},{$unset:{'agentName':'', 'monitorName':'', 'guardName':''}},false, true)

db.win_host.update({},{$unset:{'agentName':'', 'monitorName':'', 'guardName':''}},false, true)

聚合查询

在mongo中进行聚合查询

db.linux_host.aggregate([{$group:{_id:"$comId",num_tutorial:{$sum:1}}}])

select root, count(*) from linux_host group by root

/usr/local/bin/mongo --host 127.0.0.1 --port 27017 -u test -p test --authenticationDatabase admin --eval 'db.linux_host.aggregate([{$group:{_id:"$comId",count:{$sum:1}}},{$match:{count:{$gt:1}}}])' assets

总结

mongo作为一款面向文档型数据库,目前可能在使用的企业并不是很大,因为大多数企业仍在使用传统型的mysql、oracle、postgres、tidb等等。但mongodb的灵活性,也是其它数据无法比拟的,当我们的业务字段经常发生变化,其实很适合使用mongo来记录和入库,而这些是mysql等关系型数据库无法做到的。另外在使用的过程中,也需要关注查询性能问题,建立合适的索引,结合缓存的使用,来提升查询效率