Mongodb

查看数据库

show dbs

创建数据库

use 数据库名  没有则创建,有则切换到数据库

查看当前在哪个数据库

db

删除当前数据库

db.dropDatabase()

创建表

db.createCollection("表名")  创建表后才能看到数据库名

删除表

db.表名.drop()
quit # 退出shell

查看所有表

show collections

增删改查

db.表名.insert([{name:'nick',age:12},{name:'mike',age:15}]) #插入表数据(多条)  数据已存在时会报异常,反之插入
db.表名.insertOne({name:'nick',age:12}) #插入表数据(单条)  数据已存在时会报异常,反之插入
db.表名.insertMany([{name:'nick',age:12},{name:'mike',age:15}]) #插入多条
db.表名.save({name:'nick',age:12}) #插入表数据  表数据已存在则更新,反之插入 过时
db.表名.find() #查看表数据
db.表名.update() #更新
db.stats() #统计当前数据库信息
_id #在mongo中代表id

变量写法

document=[{name:'nick',age:12},{name:'mike',age:15}]
db.表名.insert(document)
db.表名.deleteOne({}) # 删除一条
db.表名.deleteMany({_id:444}) #删除指定多条
db.表名.deleteMany({}) #删除所有
> use books
switched to db books
> show collections
booksinf
> db.booksinf.find()
{ "_id" : ObjectId("62158440ec075f83d7cee995"), "name" : "<Javascript>", "major" : "web" }
{ "_id" : ObjectId("621584feec075f83d7cee996"), "name" : "<MongoDB>", "major" : "java,web" }
{ "_id" : ObjectId("621584feec075f83d7cee997"), "name" : "Redis", "major" : "java,web" }
{ "_id" : ObjectId("621584feec075f83d7cee998"), "name" : "<hadoop>", "major" : "java" }
{ "_id" : 444, "name" : "mysql", "major" : "java,web" }
{ "_id" : 3232, "name" : "java程序设计" }
> db.booksinf.deleteOne({_id:3232})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.booksinf.find()
{ "_id" : ObjectId("62158440ec075f83d7cee995"), "name" : "<Javascript>", "major" : "web" }
{ "_id" : ObjectId("621584feec075f83d7cee996"), "name" : "<MongoDB>", "major" : "java,web" }
{ "_id" : ObjectId("621584feec075f83d7cee997"), "name" : "Redis", "major" : "java,web" }
{ "_id" : ObjectId("621584feec075f83d7cee998"), "name" : "<hadoop>", "major" : "java" }
{ "_id" : 444, "name" : "mysql", "major" : "java,web" }
> db.booksinf.deleteMany({major:"java,web"})
{ "acknowledged" : true, "deletedCount" : 3 }
> db.booksinf.find()
{ "_id" : ObjectId("62158440ec075f83d7cee995"), "name" : "<Javascript>", "major" : "web" }
{ "_id" : ObjectId("621584feec075f83d7cee998"), "name" : "<hadoop>", "major" : "java" }

更新

db.表名.updateOne(
    {条件},
    {$set:{字段:值}}
)
db.表名.updateMany(
    {major:"java,web"},
    {$set:{major:"互联网"}}
)
# 将多条满足查询结果( major:"java,web")的修改成 major:"互联网"
db.表名.replaceOne(
    {name:"Lily"},
    {name:"Lisa"}
)
# Lily --> Lisa

查询数据

db.表名.find()          输出数据
db.表名.find().pretty   美化版输出数据

查询条件操作符参考表 分页查询参考

Java连接mongodb

点击 前往 maven mongo-db driver 地址

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.8.2</version>
        </dependency>
    </dependencies>
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;


/**
 * @ClassName : MongoTest
 * @Description : 连接 mongodb
 * @Author : CodeHaywire
 * @Created at 2022/3/7 10:28
 */
public class MongoTest {
    public static void main(String[] args) {
        //连接数据库
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        //创建数据库
        MongoDatabase database = mongoClient.getDatabase("testdb");
        System.out.println("Connect successfully");
        System.out.println("MongoDatabase:" + database.getName());
        //创建表
        MongoCollection col = database.getCollection("testcol");
        //准备数据
        // Document doc = new Document("name", "mm").append("des", "mmn");
        //Document doc = new Document("name", "mn").append("des", new Document("age", 12).append("sex", "男"));
        //插入数据
        //  col.insertOne(doc);
        //删除
        //col.deleteOne(doc);
        col.updateOne(new Document("name", "zhanshan"), new Document("$set", new Document("age", 21)));
    }
}

正则表达式

$regex:/parttern/

创建索引

db.collection.createIndex({"id":1})  # 为id创建升序索引
> id_1

获得索引

db.collection.getIndexes()

查询索引

db.collection.totalIndexSize()

索引的删除

db.collection.dropindexe("id_1")

批量插入数据

for(var i=1;i<=10;i++){
      db.testcol.insertOne({id:i,username:"stu"+i})
}
# 完全支持js脚本

> for(var i=1;i<=10;i++){
   db.testcol.insertOne({id:i,username:"stu"+i})
 }
······
{
        "acknowledged" : true,
        "insertedId" : ObjectId("623137db5b18f57c01c8b378")
}
······
> db.testcol.find()
······
{ "_id" : ObjectId("623137db5b18f57c01c8b36f"), "id" : 1, "username" : "stu1" }
{ "_id" : ObjectId("623137db5b18f57c01c8b370"), "id" : 2, "username" : "stu2" }
{ "_id" : ObjectId("623137db5b18f57c01c8b371"), "id" : 3, "username" : "stu3" }
{ "_id" : ObjectId("623137db5b18f57c01c8b372"), "id" : 4, "username" : "stu4" }
{ "_id" : ObjectId("623137db5b18f57c01c8b373"), "id" : 5, "username" : "stu5" }
{ "_id" : ObjectId("623137db5b18f57c01c8b374"), "id" : 6, "username" : "stu6" }
{ "_id" : ObjectId("623137db5b18f57c01c8b375"), "id" : 7, "username" : "stu7" }
{ "_id" : ObjectId("623137db5b18f57c01c8b376"), "id" : 8, "username" : "stu8" }
{ "_id" : ObjectId("623137db5b18f57c01c8b377"), "id" : 9, "username" : "stu9" }
{ "_id" : ObjectId("623137db5b18f57c01c8b378"), "id" : 10, "username" : "stu10" }
······
>db.testcol.count() #数据总条数
10

聚合

SQL 操作/函数 mongodb聚合操作
where $match
group by $group
having $match
select $project
order by $sort
limit $limit
sum() $sum
count() $sum
join $lookup (v3.2 新增)
文档
{id:1,name:"zhangsan",major:"java",score:90}
分组操作($group):
db.collection.aggregate(
[{
$group:{
_id:"$major",
score_avg:{$avg:"$score"}
       }
}])

alt

db.collection.aggregate([
    {$match:{author:"li"}}
])
db.scoreinf.insertMany([{_id:1, name:"stu1", major:"java", score:91},
{_id:2, name:"stu2", major:"web", score:80},
{_id:3, name:"stu3", major:"java", score:82},
{_id:4, name:"stu4", major:"big data", score:61},
{_id:5, name:"stu5", major:"web", score:73},
{_id:6, name:"stu6", major:"java", score:76},
{_id:7, name:"stu7", major:"web", score:94},
{_id:8, name:"stu8", major:"big data", score:79},
{_id:9, name:"stu9", major:"big data", score:93}])

# 1、统计学生总数($sum、$project)
db.scoreinf.aggregate(
[
{
    $group:{
    _id:null,  #只统计总数,不需要分组 _id设置为空(null)
    student_count:{$sum:1} #每条数据+1
    }
},
{
    $project:{    #输出时不打印id _id设置为0
    _id:0
}
     }
])
#累加
db.scoreinf.aggregate(
[
{
    $group:{
    _id:null,  #只统计总数,不需要分组 _id设置为空(null)
    student_count:{$sum:"$score"} #分数累加
    }
},
{
    $project:{    #输出时不打印id _id设置为0
    _id:0
}
     }
])
#最大值
db.scoreinf.aggregate(
[
{
    $group:{
    _id:null,
    max_score:{$max:"$score"}
    }
},
{
    $project:{
    _id:0
}
     }
])
#每个专业的人数
db.scoreinf.aggregate(
[
{
    $group:{
    _id:"$major", #以专业为分组
    student_count:{$sum:1} #每条数据+1
    }
}
])
#统计java班的平均分
#更快
db.scoreinf.aggregate(
[
{
     $match:{major:"java"}  
},
{
    $group:{
    _id:null,
    score_avg:{$avg:"$score"}
    }
}
])
#更慢
db.scoreinf.aggregate(
[
{
    $group:{
    _id:"$major",
    score_avg:{$avg:"$score"}
    }
},{
     $match:{_id:"java"}  
}
])
# 统计平均分在80分以上的专业($group,$avg,$match,$project)
1.统计各专业平均分
2.查询平均分大于等于80的专业
db.scoreinf.aggregate(
[
{
    $group:{
    _id:"$major",
    score_avg:{$avg:"$score"}
    }
},
{
    $match:{score_avg:{$gte:80}}  
},
{
    $project:{
    _id:1  #只显示专业   1:打印 0:屏蔽
    } 
}
])