MacOSX下Mongodb 安装 基础命令 java连接

Mongodb

一、macosX安装mongodb

1.下载mongodb

https://www.mongodb.com/try/download/community
在这里插入图片描述

2.解压下载好的压缩包

3.将解压出来的压缩包移动并重命名到 /usr/local/mongodb 下

mv -f /Users/yangbohan/Downloads/mongodb-macos-x86_64-4.4.0 \
/usr/local/mongodb

4.添加环境变量

PATH=${PATH}:/usr/local/mongodb/bin
vim /Users/yangbohan/.zshrc

添加一句话
export PATH=${PATH}:/usr/local/mongodb/bin
:wq 保存退出

5.新建存放数据和日志的文件夹

mkdir -p /usr/local/mongodb/db
mkdir -p /usr/local/mongodb/log

6.编写配置文件

vim /usr/local/mongodb/mongod.conf

写下

# 日志路径
logpath= /usr/local/mongodb/log/mongod.log
# 以日为计自动切割日志
logappend= true
# 数据存放路径
dbpath= /usr/local/mongodb/db
# 后台继续运行
fork= true
# ip地址 这里用自己的localhost
bind_ip= localhost
# 端口,默认27017
port= 27017

7.运行mongod

mongod -f /usr/local/mongodb/mongod.conf

在终端输入

mongo

就能进入mongodb

二、数据库常用命令

1、数据库操作

1.1 创建数据库

语法: use 数据库名称
若不存在则新建,存在则切换
例子

use articledb
1.2 显示数据库
show dbs
# 或者
show databases
1.3 数据库删除
db.dropDatabase()

2、集合操作

2.1 创建集合

显式创建(少用):
db.createCollection(name)
例:

db.createCollection("mycollection")

隐式创建(多用):
直接在集合里面插入文档,如果不存在集合则会新建

2.2 显示集合
show collections
2.3 删除集合

db.集合.drop()
例:

db.mycollection.drop()

3、文档基本crud

3.1 文档的插入
单个文档插入:

db.集合.insert({ key1 : value1 , key 2 : value 2 …})
例:

db.comment.insert({"articleid":"100000","content":"今天天气真好","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})

如果输出如下

WriteResult({ "nInserted" : 1 })

说明插入成功

多个文档插入:

db.集合.insertMany([
{key1_1:value1_1,key1_2:value2_2 …},
{key2_1:value2_1,key2_2:value2_2…},

])
例:

db.comment.insertMany([
	{"_id":"1","articleid":"100001","content":"健康很重要","userid":"1002","nickname":"相忘于江湖","createdatetime":new Date(),"likenum":NumberInt(1000),"state":"1"},
	{"_id":"2","articleid":"100002","content":"多喝开水","userid":"1005","nickname":"伊人憔悴","createdatetime":new Date(),"likenum":NumberInt(888),"state":"1"},
	{"_id":"3","articleid":"100003","content":"不喝开水","userid":"1003","nickname":"张三","createdatetime":new Date(),"likenum":NumberInt(105),"state":"1"},
	{"_id":"4","articleid":"100004","content":"什么居然是夫妻上阵?!","userid":"1003","nickname":"张三","createdatetime":new Date(),"likenum":NumberInt(732),"state":"1"},
	{"_id":"5","articleid":"100005","content":"还是买拖拉机吧,没这烦恼","userid":"1004","nickname":"celeron533","createdatetime":new Date(),"likenum":NumberInt(233),"state":"1"}
	
])

如果指定了_id字段,则主键就是该值

3.2 文档查询
查询所有:

db.集合.find()
例:

d

按条件查询 db.集合.find({key1:value1,key2,value2…})
例:

db.comment.find({"articleid":"100001"})
投影查询

db.集合.find({key1:value1},{key1:1})
例:

db.comment.find({articleid:"100001"},{articleid:1})

不显示主键

db.comment.find({articleid:"100001"},{articleid:1,_id:0})

即显示的投影列后面为1,不显示的后面为0

3.3 文档更新
db.collection.update(query,update,options)
//或
db.collection.update(
	<query>,
	<update>,
	{
		upsert:<boolean>,
		multi:<boolean>,
		writeConcern:<document>,
		collation:<document>,
		arryFilters:[<filterdocument1>, ...],
		hint <document|string>
	}
)
覆盖修改:

修改之后只剩下更新的数据
例:

db.comment.update({_id:"1"},{likenum:NumberInt(1001)})
db.comment.find({_id:"1"})

发现只剩下

{ "_id" : "1", "likenum" : 1001 }
局部修改:

只更新需要修改的字段,其他字段保留

db.comment.update({_id:"2"},{$set:{likenum:NumberInt(1001)} })
批量更新:

默认只更新符合条件的第一条,批量更新在后面加上{multi:true}
例如把userid为1003的nickname都修改为张三

db.comment.update({userid:"1003"},{$set:{nickname:"张三"}},{multi:true})

将_id为"3"的条目的likenum增长1

db.comment.update({_id:"3"},{$inc:{likenum:NumberInt(1)}})
3.4 删除文档

语法:

db.集合名称.remove(条件);

例:

db.comment.remove({_id:"1"})

删除所有数据(!!!慎用!!!

db.comment.remove({})
3.5 文档分页查询
统计查询

语法如下

db.collection.count(query,options)

例:

db.comment.count()
db.comment.count({userid:"1003"})
分页列表查询

返回指定条数的记录

//返回前三条
db.comment.find().limit(3)

//返回3 4 条
db.comment.skip(2).limit(2)
排序查询

语法:

db.COLLECTION_NAME.find().sort({KEY:1})
或
db.集合名称.find().sort(排序方式)

例:

## 升序是1 降序是-1
db.comment.find().sort({userid:-1,likenum:1})

skip(),limit(),sort()三个一起执行的时候,顺序是sort,skip,limit,和编写顺序无关

3.6 更多查询
正则复杂条件查询

语法:

db.集合.find({字段:/正则表达式/})

例:

db.comment.find({content:/开水/})
比较查询

语法:

db.集合名称.find({ "field" : { $gt: value}}) //大于:field>value
db.集合名称.find({ "field" : { $lt: value}}) //小于:field<value
db.集合名称.find({ "field" : { $gte: value}}) //大于等于:field>=value
db.集合名称.find({ "field" : { $lte: value}}) //小于等于:field<=value
db.集合名称.find({ "field" : { $ne: value}}) //不等于:field>value

例:查询评论点赞数量大于700的记录

db.comment.find({likenum:{$gt:NumberInt(700)}})
包含查询

例:

//查询评论的集合中userid字段包含1003或1004的文档
db.comment.find({userid:{$in:["1003","1004"]}})
//查询评论的集合中userid字段不包含1003或1004的文档
db.comment.find({userid:{$nin:["1003","1004"]}})
条件查询

格式:

$and:[ { },{ }, { } ]

例:

//查询评论集合中likenum大于等于700并且小于2000的文档
db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
//查询评论集合中userid为1003或者点赞数小于1000的文档记录
db.comment.find({$or:[{userid:"1003"},{likenum:{$lt:1000}}]})

4、索引

4.1 索引的查看

说明:返回一个集合中所有索引的数组

语法:

db.collection.getIndexes()

例:

db.comment.getIndexes()
4.2 索引的创建
单索引

说明:在集合上创建索引

语法:

db.collection.createIndex(keys,options)

参数:

在这里插入图片描述

options(更多选项)列表:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4DSVdV8D-1600330549789)(/Users/yangbohan/Library/Application Support/typora-user-images/image-20200917150635224.png)]

name与unique为常用选项

例:

db.comment.createIndex({userid:1})
复合索引

useridnickname同时建立复合(Compound)索引:

db.comment.createIndex({userid:1,nickname:-1})
4.3 索引的移除
指定索引的移除

语法:

db.collection.dropIndex(index)

参数:

ParameterTypeDescription
indexstring or document指定要删除的索引,可以通过索引名称或索引规范文档指定索引。若要删除文本索引,请指定索引名称。

例:

db.comment.dropIndex({userid:1})
删除所有的索引

语法:

db.collection.dropIndexes()

例:

db.comment.dropIndexes()
4.4 索引的使用
查看执行计划

语法:

db.collection.find(query,options).explain(options)

例:

db.comment.find({userid:"1003"}).explain()

# 以下为输出信息
> db.comment.find({userid:"1003"}).explain()
{
	"queryPlanner" : {
		"plannerVersion" : 1,
		"namespace" : "articledb.comment",
		"indexFilterSet" : false,
		"parsedQuery" : {
			"userid" : {
				"$eq" : "1003"
			}
		},
		"queryHash" : "37A12FC3",
		"planCacheKey" : "37A12FC3",
		"winningPlan" : {
			"stage" : "COLLSCAN", # 此处为全局扫描
			"filter" : {
				"userid" : {
					"$eq" : "1003"
				}
			},
			"direction" : "forward"
		},
		"rejectedPlans" : [ ]
	},
	"serverInfo" : {
		"host" : "MacBook-Pro.local",
		"port" : 27017,
		"version" : "4.4.0",
		"gitVersion" : "563487e100c4215e2dce98d0af2a6a5a2d67c5cf"
	},
	"ok" : 1
}

加上索引之后

db.comment.createIndex({userid:1})
db.comment.find({userid:"1003"}).explain()

#以下为输出信息
> db.comment.find({userid:"1003"}).explain()
{
	"queryPlanner" : {
		"plannerVersion" : 1,
		"namespace" : "articledb.comment",
		"indexFilterSet" : false,
		"parsedQuery" : {
			"userid" : {
				"$eq" : "1003"
			}
		},
		"queryHash" : "37A12FC3",
		"planCacheKey" : "7FDF74EC",
		"winningPlan" : {
			"stage" : "FETCH",	# 此处变为抓取
			"inputStage" : {
				"stage" : "IXSCAN",
				"keyPattern" : {
					"userid" : 1
				},
				"indexName" : "userid_1",
				"isMultiKey" : false,
				"multiKeyPaths" : {
					"userid" : [ ]
				},
				"isUnique" : false,
				"isSparse" : false,
				"isPartial" : false,
				"indexVersion" : 2,
				"direction" : "forward",
				"indexBounds" : {
					"userid" : [
						"[\"1003\", \"1003\"]"
					]
				}
			}
		},
		"rejectedPlans" : [ ]
	},
	"serverInfo" : {
		"host" : "MacBook-Pro.local",
		"port" : 27017,
		"version" : "4.4.0",
		"gitVersion" : "563487e100c4215e2dce98d0af2a6a5a2d67c5cf"
	},
	"ok" : 1
}
涵盖的查询

Covered Queries

当查询条件和查询条件的投影仅包含索引字段时,MongoDB直接从索引返回结果,而不扫描任何文档或将文档带入内存。

三、mongodb与java连接

mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。

官方驱动说明和下载:https://mongodb.github.io/mongo-java-driver/

官方驱动示例文档:https://mongodb.github.io/mongo-java-driver/4.1/driver/getting-started/installation/

https://mongodb.github.io/mongo-java-driver/4.1/driver/getting-started/quick-start/

1、环境搭建

使用maven构建项目

使用Idea新建一个maven空项目,在pom.xml文件中加入依赖

<project ....>
  ...
<dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.1.0-beta2</version>
        </dependency>
    </dependencies>
  ...
</project>

2、快速入门

在/src/main/java 下新建Mongodb_test.java

写入

import com.mongodb.ConnectionString;
import com.mongodb.client.*;
import org.bson.Document;


public class Mongodb_Test {
    public static void main(String[] args) {
        // 1.创建链接
        MongoClient mongoClient = MongoClients.create();
        // 2.打开数据库articledb
        MongoDatabase mydb = mongoClient.getDatabase("articledb");
        // 3.获取集合comment
        MongoCollection<Document> collection = mydb.getCollection("comment");
        // 4.集合查询
        FindIterable<Document> documents = collection.find();
        // 5.循环打印
        for(Document document:documents){
            System.out.println(document);
        }
        // 6.连接关闭
        mongoClient.close();
    }
}

运行 可得到

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值