Mongodb的基本使用

举报
江湖有缘 发表于 2023/02/08 17:55:35 2023/02/08
【摘要】 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

③查看某个表全部内容

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

五、数据的增删查改

1.查——数据的查询

①某个表的所有数据查询

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" }
> 

【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。