DataGrip连接MongoDB及CRUD操作

勤奋不是嘴上说说而已,而是实际的行动,在勤奋的苦度中持之以恒,永不退却。业精于勤,荒于嬉;行成于思,毁于随。在人生的仕途上,我们毫不迟疑地选择勤奋,她是几乎于世界上一切成就的催产婆。只要我们拥着勤奋去思考,拥着勤奋的手去耕耘,用抱勤奋的心去对待工作,浪迹红尘而坚韧不拔,那么,我们的生命就会绽放火花,让人生的时光更加的闪亮而精彩。

导读:本篇文章讲解 DataGrip连接MongoDB及CRUD操作,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

背景

DataGrip作为一款超级强悍的数据库工具,支持MongoDB是一件必然的事情。早期版本应该不支持;另外,IDEA内嵌简单版本的数据库连接插件。测试验证下来,IDEA 2020.1.4版本支持连接MongoDB,DataGrip 2021.1.2 版本支持连接MongoDB(更早版本应该也支持)。

连接

新建数据源,下载驱动,填写正确无误的连接串信息,然后点击test connection测试是否可以连通。

there are no users authenticated

报错信息:

com.mongodb.MongoCommandException: Command failed with error 13 (Unauthorized): 'there are no users authenticated' on server 222.111.000.333:7998.

出错的原因为:连接串仅有某个database的权限,但在DataGrip的databases配置里选择所有的数据库
在这里插入图片描述
解决方法:仅选择有权限的database schema。如果选中所有的数据库,则DataGrip在测试连接时,会尝试获取所有数据库的信息。

CRUD

在DataGrip Console,即SQL输入框里面,做如下测试验证。

基础

select * from my_col
等价于
db.getCollection('my_col').find({});
在这里插入图片描述
注意:右上角需要选择schema。

下面这种指定schema的查询不生效,因为getCollection函数里面的字符串必须是一个集合名称:db.getCollection('test.my_col').find({});

获取count(*)数据:

select count(*) from my_col
等价于

db.getCollection('my_col').count();
db.getCollection('my_col').countDocuments();
db.getCollection('my_col').estimatedDocumentCount();

指定查询字段

select user_name from my_col
等价于
db.getCollection('my_col').find({}, {user_name:1});
默认情况下,MongoDB查询会返回_id字段,如果不想要返回此字段,则:
db.getCollection('my_col').find({}, {user_name:1, _id:0});

条件查询

select * from my_col where model_id > 1000 and isauto = 1 and model_name like '%test%';
等价于

db.getCollection('my_col').find({model_id: {"$gt": 1000}, isauto: 1, model_name: /test/});

模糊查询

SQL写法:

select * from my_col where model_name like '%test%';
select * from my_col where model_name like 'test%';// 以test开头
select * from my_col where model_name like '%test';// 以test结尾

对应的MongoDB查询语法:

db.getCollection('my_col').find({model_name: /test/});
db.getCollection('my_col').find({model_name: /^test/});// 以test开头
db.getCollection('my_col').find({model_name: /});// 以test结尾???

正则查询

db.getCollection('my_col').find(test:/a/i);

更新字段

db.getCollection("my_col").updateOne({_id: new ObjectId("621f5382f358f42224829ad5")}, {"$set": {model_name: "1223etest123456"}})
   还可以用正则表达式来查询数据,mongo使用$regex来设置字段匹配正则表达式,其实上面就是简化版的正则表达式了。

日期查询

稍微复杂一点的查询语句,如:

结论

支持以常规SQL的写法,来查询MongoDB数据库。

验证下来:

  1. 2021.1.2版本不支持
  2. 2021.2.1版本支持

参考

MongoDB正则

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142130.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!