Mongodb的基本使用

一、进入mongodb数据库

[root@node-3 ~]# mongo
MongoDB shell version v5.0.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c5000143-da5e-48fe-9fe3-a0cd8765abb6") }
MongoDB server version: 5.0.5
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
rs0:PRIMARY> 

二、mongodb的基本操作

1.查看mongodb的版本

[root@node-3 ~]# mongo --version
MongoDB shell version v5.0.5
Build Info: {
    "version": "5.0.5",
    "gitVersion": "d65fd89df3fc039b5c55933c0f71d647a54510ae",
    "openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "rhel70",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

2.远程客户端连接

[root@node-4 ~]# mongo --host 192.168.3.13 -u root -p redhat 
MongoDB shell version v5.0.5
connecting to: mongodb://192.168.3.13:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("32846f84-f393-47ce-bbdb-a9801f7a3f44") }
MongoDB server version: 5.0.5
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting: 
        2022-01-24T14:34:53.592+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2022-01-24T14:34:53.592+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
rs0:PRIMARY> 

3.退出数据库

rs0:PRIMARY> quit()

4.停止mongodb数据库

systemctl stop mongodb

5.设置mongodb开机自启

 systemctl enable --now mongod

三、mongdb内的基本操作

1.查询版本

rs0:PRIMARY> db.version()
5.0.5

2.查看服务器状态

rs0:PRIMARY> db.serverStatus()
{
	"ok" : 0,
	"errmsg" : "command serverStatus requires authentication",
	"code" : 13,
	"codeName" : "Unauthorized",
	"$clusterTime" : {
		"clusterTime" : Timestamp(1643009776, 1),
		"signature" : {
			"hash" : BinData(0,"HPBEnEKbxKOF+63qcIDXa33Ex5E="),
			"keyId" : NumberLong("7055349082151190532")
		}
	},
	"operationTime" : Timestamp(1643009776, 1)
}
rs0:PRIMARY> 

3.查看数据库环境信息

rs0:PRIMARY> db.serverBuildInfo()
{
	"version" : "5.0.5",
	"gitVersion" : "d65fd89df3fc039b5c55933c0f71d647a54510ae",
	"modules" : [ ],
	"allocator" : "tcmalloc",
	"javascriptEngine" : "mozjs",
	"sysInfo" : "deprecated",
	"versionArray" : [
		5,
		0,
		5,
		0
	],
	"openssl" : {
		"running" : "OpenSSL 1.0.1e-fips 11 Feb 2013",
		"compiled" : "OpenSSL 1.0.1e-fips 11 Feb 2013"
	},
	"buildEnvironment" : {
		"distmod" : "rhel70",
		"distarch" : "x86_64",
		"cc" : "/opt/mongodbtoolchain/v3/bin/gcc: gcc (GCC) 8.5.0",
		"ccflags" : "-Werror -include mongo/platform/basic.h -fasynchronous-unwind-tables -ggdb -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -fno-omit-frame-pointer -fno-strict-aliasing -O2 -march=sandybridge -mtune=generic -mprefer-vector-width=128 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-const-variable -Wno-unused-but-set-variable -Wno-missing-braces -fstack-protector-strong -Wa,--nocompress-debug-sections -fno-builtin-memcmp",
		"cxx" : "/opt/mongodbtoolchain/v3/bin/g++: g++ (GCC) 8.5.0",
		"cxxflags" : "-Woverloaded-virtual -Wno-maybe-uninitialized -fsized-deallocation -std=c++17",
		"linkflags" : "-Wl,--fatal-warnings -pthread -Wl,-z,now -fuse-ld=gold -fstack-protector-strong -Wl,--no-threads -Wl,--build-id -Wl,--hash-style=gnu -Wl,-z,noexecstack -Wl,--warn-execstack -Wl,-z,relro -Wl,--compress-debug-sections=none -Wl,-z,origin -Wl,--enable-new-dtags",
		"target_arch" : "x86_64",
		"target_os" : "linux",
		"cppdefines" : "SAFEINT_USE_INTRINSICS 0 PCRE_STATIC NDEBUG _XOPEN_SOURCE 700 _GNU_SOURCE _FORTIFY_SOURCE 2 BOOST_THREAD_VERSION 5 BOOST_THREAD_USES_DATETIME BOOST_SYSTEM_NO_DEPRECATED BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS BOOST_ENABLE_ASSERT_DEBUG_HANDLER BOOST_LOG_NO_SHORTHAND_NAMES BOOST_LOG_USE_NATIVE_SYSLOG BOOST_LOG_WITHOUT_THREAD_ATTR ABSL_FORCE_ALIGNED_ACCESS"
	},
	"bits" : 64,
	"debug" : false,
	"maxBsonObjectSize" : 16777216,
	"storageEngines" : [
		"devnull",
		"ephemeralForTest",
		"wiredTiger"
	],
	"ok" : 1,
	"$clusterTime" : {
		"clusterTime" : Timestamp(1643009896, 1),
		"signature" : {
			"hash" : BinData(0,"+ocBhFmzeAmQKSZycIjaX7V5DnY="),
			"keyId" : NumberLong("7055349082151190532")
		}
	},
	"operationTime" : Timestamp(1643009896, 1)
}

四、数据库的增删改查

1.进入到某个数据库

rs0:PRIMARY> use admin
switched to db admin

2.查——查看数据库的库和表

①查看所有数据库

查看当前所有数据库列表

rs0:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
huawei  0.000GB
local   0.001GB

②.查看数据库内所有集合

查看数据库内所有集合

rs0:PRIMARY> show tables
class
student

③查看某个集合数据

查看class集合内的所有文档数据

rs0:PRIMARY> db.class.find()
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }
rs0:PRIMARY>

3.增——新建数据库和集合

①新建数据库

rs0:PRIMARY> use redhat
switched to db redhat

②新建集合

rs0:PRIMARY> db.createCollection("class")
{
	"ok" : 1,
	"$clusterTime" : {
		"clusterTime" : Timestamp(1643023713, 1),
		"signature" : {
			"hash" : BinData(0,"7SNRK8H9v7OkxWIPp1zPMMMpgMc="),
			"keyId" : NumberLong("7055349082151190532")
		}
	},
	"operationTime" : Timestamp(1643023713, 1)
}

4.删——删除集合、数据库、文档

①删除集合

> db.teacher.drop()
true
> show tables;
class
student
> 

②删除数据库

> use huawei;
switched to db huawei
> show tables;
class
> db.dropDatabase();
{ "ok" : 1 }
> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

③删除文档

db.class.remove({"type":"televison"})

五、数据的增删查改

1.查——数据的查询

①某个集合内所有文档数据

查看class集合内所有文档数据

rs0:PRIMARY> db.class.find({"type":"televison"})
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }
rs0:PRIMARY> 

②根据条件查找数据

s0:PRIMARY> db.class.find({"type":"televison"})
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }
rs0:PRIMARY> 

③以固定格式显示查找结果

rs0:PRIMARY> db.class.find().pretty()
{
	"_id" : ObjectId("61e9791e0e4afa869cc30dd6"),
	"type" : "televison",
	"price" : "3999",
	"xinghao" : "huawei",
	"desc" : "xxx"
}
{
	"_id" : ObjectId("61eea145a3d5c6b913b29beb"),
	"name" : "natasha",
	"age" : "18",
	"genden" : "female"
}
rs0:PRIMARY> 

2.增——新建数据

 db.class.insert({ "name": "natasha", "age": "18", "genden": "female" });

3.改——修改数据

①更新数据

db.class.update({"type" : "phone"},{$set:{ "type": "televison"}})

②save()方法——新文档替换旧文档

> db.class.find()
{ "_id" : ObjectId("61e978a80e4afa869cc30dd5"), "name" : "natasha", "age" : "18", "genden" : "female" }
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }

将新文档替换ID为"61e978a80e4afa869cc30dd5"

db.class.save({
    "_id" : ObjectId("61e978a80e4afa869cc30dd5"),
    "title" : "MongoDB",
    "description" : "MongoDB 是一个 Nosql 数据库",
    "by" : "Runoob",
    "url" : "http://www.runoob.com",
    "tags" : [
            "mongodb",
            "NoSQL"
    ],
    "likes" : 110
})
> db.class.find()
{ "_id" : ObjectId("61e978a80e4afa869cc30dd5"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "Runoob", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 }
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }
> 

4.删除数据

> db.class.remove({"likes" : 110}, {justone: true})
WriteResult({ "nRemoved" : 1 })
> db.class.find()
{ "_id" : ObjectId("61e9791e0e4afa869cc30dd6"), "type" : "televison", "price" : "3999", "xinghao" : "huawei", "desc" : "xxx" }
> 

MongoDB是一个面向文档的数据库,目前由10gen开发并维护,它的功能丰富,齐全,完全可以替代MySQL。在使用MongoDB做产品原型的过程中,我们总结了MonogDB的一些亮点:使用JSON风格语法,易于掌握和理解:MongoDB使用JSON的变种BSON作为内部存储的格式和语法。针对MongoDB操作使用JSON风格语法,客户端提交或接收的数据都使用JSON形式来展现。相对于SQL来说,更加直观,容易理解和掌握。Schema-less,支持嵌入子文档:MongoDB是一个Schema-free的文档数据库。一个数据库可以有多个Collection,每个Collection是Documents的集合。Collection和Document和传统数据库的Table和Row并不对等。无需事先定义Collection,随时可以创建。Collection中可以包含具有不同schema的文档记录。 这意味着,你上一条记录中的文档有3个属性,而下一条记录的文档可以有10个属性,属性的类型既可以是基本的数据类型(如数字、字符串、日期等),也可以是数组或者散列,甚至还可以是一个子文档(embed document)。这样,可以实现逆规范化(denormalizing)的数据模型,提高查询的速度。图1 MongoDB是一个Schema-free的文档数据库图2是一个例子,作品和评论可以设计为一个collection,评论作为子文档内嵌在art的comments属性中,评论的回复则作为comment子文档的子文档内嵌于replies属性。按照这种设计模式,只需要按照作品id检索一次,即可获得所有相关的信息了。在MongoDB中,不强调一定对数据进行Normalize ,很多场合都建议De-normalize,开发人员可以扔掉传统关系数据库各种范式的限制,不需要把所有的实体都映射为一个Collection,只需定义最顶级的class。MongoDB的文档模型可以让我们很轻松就能将自己的Object映射到collection中实现存储。图2 MongoDB支持嵌入子文档简单易用的查询方式:MongoDB中的查询让人很舒适,没有SQL难记的语法,直接使用JSON,相当的直观。对不同的开发语言,你可以使用它最基本的数组或散列格式进行查询。配合附加的operator,MongoDB支持范围查询,正则表达式查询,对子文档内属性的查询,可以取代原来大多数任务的SQL查询。CRUD更加简单,支持in-place update:只要定义一个数组,然后传递给MongoDB的insert/update方法就可自动插入或更新;对于更新模式,MongoDB支持一个upsert选项,即:“如果记录存在那么更新,否则插入”。MongoDB的update方法还支持Modifier,通过Modifier可实现在服务端即时更新,省去客户端和服务端的通讯。这些modifer可以让MongoDB具有和Redis、Memcached等KV类似的功能:较之MySQL,MonoDB更加简单快速。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖有缘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值