背景

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正则

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐