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
相关文章
|
24天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第21天】本文探讨了MongoDB Atlas的核心特性、实践应用及对云原生数据库未来的思考。MongoDB Atlas作为MongoDB的云原生版本,提供全球分布式、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了云原生数据库的未来趋势,如架构灵活性、智能化运维和混合云支持,并分享了实施MongoDB Atlas的最佳实践。
|
25天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第20天】本文探讨了MongoDB Atlas的核心特性、实践应用及对未来云原生数据库的思考。MongoDB Atlas作为云原生数据库服务,具备全球分布、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了实施MongoDB Atlas的最佳实践和职业心得,展望了云原生数据库的发展趋势。
|
26天前
|
存储 NoSQL MongoDB
MongoDB 数据库引用
10月更文挑战第20天
17 1
|
1月前
|
存储 NoSQL MongoDB
基于阿里云数据库MongoDB版,微财数科“又快又稳”服务超7000万客户
选择MongoDB主要基于其灵活的数据模型、高性能、高可用性、可扩展性、安全性和强大的分析能力。
|
1月前
|
存储 NoSQL MongoDB
mongodb的数据库表怎么创建
在此过程中,理解并掌握这些基本操作,是深入探索MongoDB魅力,乃至构建高效数据解决方案的关键所在。通过实践,您将更加深刻地体会到这种随需应变的数据管理模式带来的便利与效率提升。
25 0
|
1月前
|
存储 NoSQL MongoDB
小川科技携手阿里云数据库MongoDB:数据赋能企业构建年轻娱乐生态
基于MongoDB灵活模式的特性,小川实现了功能的快速迭代和上线,而数据库侧无需任何更改
|
1月前
|
运维 NoSQL BI
简道云搭载阿里云MongoDB数据库,帮助数以万计企业重构业务系统
通过与MongoDB和阿里云团队的合作,让简道云少走了弯路,保障了线上服务的长期稳定运行,提高了吞吐效率,并相应降低了线上运行成本
|
1月前
|
存储 关系型数据库 MySQL
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB区别,适用场景
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB——特点、性能、扩展性、安全性、适用场景比较
|
2月前
|
存储 NoSQL 关系型数据库
非关系型数据库-MongoDB技术(二)
非关系型数据库-MongoDB技术(二)
|
2月前
|
NoSQL 关系型数据库 MongoDB
非关系型数据库-MongoDB技术(一)
非关系型数据库-MongoDB技术(一)