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
相关文章
|
10天前
|
存储 NoSQL 关系型数据库
非关系型数据库-MongoDB技术(二)
非关系型数据库-MongoDB技术(二)
|
10天前
|
NoSQL 关系型数据库 MongoDB
非关系型数据库-MongoDB技术(一)
非关系型数据库-MongoDB技术(一)
|
2月前
|
运维 监控 NoSQL
【MongoDB 复制集秘籍】Secondary 同步慢怎么办?深度解析与实战指南,让你的数据库飞速同步!
【8月更文挑战第24天】本文通过一个具体案例探讨了MongoDB复制集中Secondary成员同步缓慢的问题。现象表现为数据延迟增加,影响业务运行。经分析,可能的原因包括硬件资源不足、网络状况不佳、复制日志错误等。解决策略涵盖优化硬件(如增加内存、升级CPU)、调整网络配置以减少延迟以及优化MongoDB配置(例如调整`oplogSize`、启用压缩)。通过这些方法可有效提升同步效率,保证系统的稳定性和性能。
48 4
|
3天前
|
存储 NoSQL 前端开发
前端轻量级数据库mongodb
【10月更文挑战第2天】MongoDB 是一个基于分布式文件存储的开源数据库系统,不属于前端轻量级数据库,而是后端数据库。它使用 BSON 格式存储数据,支持复杂的数据结构,适用于内容管理系统、物联网等领域。MongoDB 通过动态模式和面向对象的数据存储方式,提供了灵活的数据模型。在 Web 应用中,它通常作为后端存储,通过 API 与前端交互,实现高效的数据管理和实时更新。
|
2月前
|
C# 开发者 Windows
全面指南:WPF无障碍设计从入门到精通——让每一个用户都能无障碍地享受你的应用,从自动化属性到焦点导航的最佳实践
【8月更文挑战第31天】为了确保Windows Presentation Foundation (WPF) 应用程序对所有用户都具备无障碍性,开发者需关注无障碍设计原则。这不仅是法律要求,更是社会责任,旨在让技术更人性化,惠及包括视障、听障及行动受限等用户群体。
51 0
|
2月前
|
Java 前端开发 Spring
技术融合新潮流!Vaadin携手Spring Boot、React、Angular,引领Web开发变革,你准备好了吗?
【8月更文挑战第31天】本文探讨了Vaadin与Spring Boot、React及Angular等主流技术栈的最佳融合实践。Vaadin作为现代Java Web框架,与其他技术栈结合能更好地满足复杂应用需求。文中通过示例代码展示了如何在Spring Boot项目中集成Vaadin,以及如何在Vaadin项目中使用React和Angular组件,充分发挥各技术栈的优势,提升开发效率和用户体验。开发者可根据具体需求选择合适的技术组合。
36 0
|
2月前
|
存储 SQL NoSQL
探索数据存储的多样性:深入比较Entity Framework Core与NoSQL数据库MongoDB的特性与应用
【8月更文挑战第31天】在现代软件开发中,选择合适的数据存储方案对应用性能至关重要。本文通过对比Entity Framework Core(EF Core)和MongoDB,探讨两者的特点及适用场景。EF Core作为.NET生态中的ORM,简化了SQL数据库的交互;MongoDB则是一种灵活的NoSQL文档数据库,适合处理大量非结构化数据。两者在数据模型、查询方式及性能上各有优势,选择时需根据具体应用需求决定。理解这些差异有助于做出更合理的技术选型。
32 0
|
18天前
|
NoSQL 关系型数据库 MySQL
微服务架构下的数据库选择:MySQL、PostgreSQL 还是 NoSQL?
在微服务架构中,数据库的选择至关重要。不同类型的数据库适用于不同的需求和场景。在本文章中,我们将深入探讨传统的关系型数据库(如 MySQL 和 PostgreSQL)与现代 NoSQL 数据库的优劣势,并分析在微服务架构下的最佳实践。
|
20天前
|
存储 SQL 关系型数据库
使用MySQL Workbench进行数据库备份
【9月更文挑战第13天】以下是使用MySQL Workbench进行数据库备份的步骤:启动软件后,通过“Database”菜单中的“管理连接”选项配置并选择要备份的数据库。随后,选择“数据导出”,确认导出的数据库及格式(推荐SQL格式),设置存储路径,点击“开始导出”。完成后,可在指定路径找到备份文件,建议定期备份并存储于安全位置。
160 11
|
15天前
|
存储 SQL 关系型数据库
MySQL的安装&数据库的简单操作
本文介绍了数据库的基本概念及MySQL的安装配置。首先解释了数据库、数据库管理系统和SQL的概念,接着详细描述了MySQL的安装步骤及其全局配置文件my.ini的调整方法。文章还介绍了如何启动MySQL服务,包括配置环境变量和使用命令行的方法。最后,详细说明了数据库的各种操作,如创建、选择和删除数据库的SQL语句,并提供了实际操作示例。
58 13
MySQL的安装&数据库的简单操作
下一篇
无影云桌面