Mongodb的基本使用

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 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" }
>
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。   相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
NoSQL 关系型数据库 MySQL
Linux平台下安装部署MongoDB数据库及基本使用(1)
Linux平台下安装部署MongoDB数据库及基本使用(1)
456 0
|
存储 JSON NoSQL
【mongo 系列】mongodb 学习二,mongodb 的基本使用梳理
• 文档 是 mongodb 的最小数据集单位,是多个键值对有序租户在一起的数据单元,类似于关系型数据库的记录
255 4
|
存储 NoSQL Ubuntu
MongoDB的「Linux」安装及基本使用
MongoDB的「Linux」安装及基本使用
1076 0
MongoDB的「Linux」安装及基本使用
|
NoSQL MongoDB 数据库
Mongodb数据库的基本使用
Mongodb数据库的基本使用
238 1
|
NoSQL 关系型数据库 MySQL
SpringBoot高级篇MongoDB之修改基本使用姿势
本篇依然是MongoDB curd中的一篇,主要介绍document的更新,主要内容如下 常见类型成员的修改 数组类型成员的增删改 document类型成员的增删改
537 0
|
NoSQL 数据可视化 JavaScript
明了 | MongoDB 外键的基本使用
小小继续进行学习,这次学习的内容是MongoDB外键的基本使用。
1241 0
|
NoSQL 数据库 索引
|
NoSQL 数据库 MongoDB
MongoDB的基本使用
use library 使用use函数切换已有的数据库或创建新的数据库   show dbs 查看MongoDB中目前所有可用的数据库   show collections 查看当前数据库中的所有集合   在集合中插入数据 >document = ({"Type":"Book","Title":"Definitive Guide to MongoDB 2nd ed.
637 0
|
24天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第21天】本文探讨了MongoDB Atlas的核心特性、实践应用及对云原生数据库未来的思考。MongoDB Atlas作为MongoDB的云原生版本,提供全球分布式、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了云原生数据库的未来趋势,如架构灵活性、智能化运维和混合云支持,并分享了实施MongoDB Atlas的最佳实践。