MongoDB使用手册_v1.0
- 格式:pdf
- 大小:364.27 KB
- 文档页数:20
mongodb基本操作命令MongoDB是一个开源的文档型数据库,具有高性能、高可扩展性、高可用性等优点。
在使用MongoDB时,我们需要掌握一些基本操作命令,以便更好地管理和维护我们的数据库。
下面将详细介绍MongoDB的基本操作命令。
一、连接和退出1.连接MongoDB在命令行中输入以下命令可以连接到MongoDB:mongo如果你需要连接到指定主机上的MongoDB,则可以使用以下命令:mongo --host <hostname>其中<hostname>是指要连接的主机名或IP地址。
2.退出MongoDB要退出MongoDB,可以输入以下命令:exit二、数据库操作1.创建数据库在MongoDB中,我们可以使用以下命令来创建一个新的数据库:use <database_name>其中<database_name>是指你要创建的数据库名称。
2.查看当前数据库要查看当前正在使用的数据库,可以使用以下命令:db3.查看所有数据库要查看所有已经存在的数据库列表,可以使用以下命令:show dbs4.删除数据库要删除一个已经存在的数据库,可以使用以下命令:use <database_name>db.dropDatabase()其中<database_name>是指你要删除的数据库名称。
三、集合操作1.创建集合在MongoDB中,我们可以使用以下命令来创建一个新的集合:db.createCollection(<collection_name>)其中<collection_name>是指你要创建的集合名称。
2.查看集合要查看已经存在的集合列表,可以使用以下命令:show collections3.删除集合要删除一个已经存在的集合,可以使用以下命令:db.<collection_name>.drop()其中<collection_name>是指你要删除的集合名称。
MongoDB安装及维护简明指导手册1准备工作1.1下载到/download网站地址下载安装包,由于我们的Server是64位的,因此我下载的是64位的对应版本;注意:由于MongoDB的版本命名规则通常都是偶数为稳定版本,而奇数为实验版本,所以最好下载推荐的稳定发布版本,比如我选择2.2.0;1.2上传1.3创建用户、组[root@localhost bin]#groupadd mongodb//创建mongodb的组[root@localhost bin]#useradd –g mongodb mongodb//创建mongodb的用户1.4创建好数据、日志目录由于MongoDB支持多实例启动,只需要不同时使用一个数据目录即可;所以数据目录和日志目录可以随意创建,当然易读是必须的;例子:在根目录创建data以及其下的mongodb_data和mongodb_log两个目录[root@localhost bin]#mkdir –p /data/ mongodb_data//创建data目录以及其子目录mongodb_data[root@localhost bin]#mkdir –p /data/ mongodb_log //创建data目录以及其子目录mongodb_log另外别忘了把data这个目录下的mongodb_xxx这几个和mongodb强相关的所有权交给mongo用户和组啊,不然到时候运行可能会有问题的!例子:[root@localhost bin]#chown –R mongodb:mongodb /data/ mongodb_data//将该目录及其下所有内容的拥有权交给mongodb组的mongodb用户使用;[root@localhost bin]#chown –R mongodb:mongodb /data/ mongodb_log//将该目录及其下所有内容的拥有权交给mongodb组的mongodb用户使用;2安装2.1解压这点没啥好说的,直接用tar命令解压即可;例子:[root@localhost bin]#tar zxvf mongodb-linux-x86_64-2.0.7.tgz//直接解压即可注意:这里有新的文件格式,不是tar.gz而是tgz,但是没关系;tar命令照样能解决;2.2安装MongoDB不需要安装,解压之后直接就可以用;但是,我们也要把他挪一个窝,并且给指定用户和组来用;例子:[root@localhost bin]#mv mongodb-linux-x86_64-2.0.7 /usr/local/mongodb//挪到/usr/local下,改名叫mongodb了;[root@localhost bin]#chown –R mongodb:mongodb /usr/local/mongodb//将该目录及其下所有内容的拥有权交给mongodb组的mongodb用户使用;直接运行mongod这个文件也可以启动,但是建议加上一些必要参数,详见下一章节;3启动、停止服务配置3.1环境变量配置这里其实没有什么环境变量可以配的只不过是为了方便在任何目录下都能运行到mongo这个程序,稍稍配置了一下:3.1.1直接把常用的文件mongo复制到根目录下的sbin,这个是最简单的方法,因为sbin目录已经默认被加到了PATH的环境变量中了;例子:[root@localhost bin]#cp /usr/local/mongodb/bin/mongo /sbin/mongo//从bin目录下复制到sbin;3.1.2修改profile文件中的Path定义,加入mongo文件所在目录地址;例子:[root@localhost bin]#vi /etc/profile在PATH这个变量的后面追加以下内容::/usr/local/mongodb/bin如下图:然后:wq保存退出Source一下该文件,使环境变量生效[root@localhost bin]#source /etc/profile注意:一定要用符号“:”来分隔之前的字符串3.2参数方式启动mongodb简单的启动,只需要加上两个必填参数启动,一个是dbpath,还有一个是logpath;分别指向到准备工作中创建好的数据、日志目录即可启动;例子:[root@localhost bin]#mongod --dbpath=/data/mongodb_data/ --logpath=/data/mongodb_log/mongodb.log --logappend&//指明了dbpath和logpath这两个路径,使mongodb有了可以正确存储数据和日志的地方;//并且还加了一个参数--logappend,避免覆写已存在的日志文件,让它另存新的日志文件;//最后有一个符号&,让它后台运行去吧,避免关掉会话之后这个进程也挂了;当然,也有一个参数可以达到相同的效果,--fork,后面会讲到;还有一些常用到的启动配置参数,拉出来我们一起围观一下:数据文件存放路径,每个数据库会在其中创建一个子目录,用于防止同一个实例多次运行的mongod.lock 也保存在此目录中。
mongodb 数据库基本操作
MongoDB 是一种NoSQL 数据库系统,使用BSON(Binary JSON)格式存储数据。
下面是MongoDB 的基本操作指南:
1. 连接到MongoDB 数据库
使用MongoDB 的客户端mongoshell 可以连接上本地数据库、远程数据库或者MongoDB Atlas 等服务。
2. 创建数据库或集合
MongoDB 使用的是以其独有的方式命名的数据库和集合,在mongoshell 中可以创建一个新的数据库或集合。
3. 插入数据
在MongoDB 中,数据以文档的方式存储。
可在mongoshell 中插入新数据或用程序编写插入数据的语句。
4. 查询数据
可以使用mongoshell 中提供的查询语言,如find(),可在其中指定查询条件和结果集的排序等信息。
5. 更新数据
使用update() 方法可以轻松地更新数据。
6. 删除数据
在MongoDB 中,使用remove() 方法可以删除数据。
还可以使用drop() 方法删除整个集合。
7. 索引
MongoDB 中的索引与传统关系型数据库中的索引类似,可提高查询语句的执行效率。
8. 备份和恢复数据
MongoDB 提供了备份和恢复数据库的工具,您可以选择在定期备份数据来保护数据库。
以上是MongoDB 数据库的基本操作指南,需要根据应用场景和业务需求进行具体操作。
MongoDB_使⽤⼿册-中⽂版MongoDB 使⽤⼿册-中⽂版⽬录第1章MONGODB简介 (4)1.1功能特点 (4)1.2适⽤范围 (4)第2章MONGODB下载及安装 (5)2.1下载地址 (5)2.2安装⽅法 ............................................................................................................ 错误!未定义书签。
第3章MONGODB语法.. (6)3.1基本命令 (6)3.1.1.启动mongodb (6)3.1.2.停⽌mongodb (6)3.2SQL语法 (7)3.2.1.基本操作 (7)3.2.2.数据集操作 (8)第4章JAVA操作MONGODB (10)4.1正在整理中 (10)第5章其它 (10)5.1正在整理中 (10)第1章MongoDB简介1.1功能特点官⽅⽹址:/doc/6715122145.html/MongoDB是⼀个基于分布式⽂件存储的数据库开源项⽬。
由C++语⾔编写,旨在为WEB应⽤提供可护展的⾼性能数据存储解决⽅案。
它的特点是可扩展,⾼性能,易使⽤,模式⾃由,存储数据⾮常⽅便等,主要功能特性有:◆⾯向⽂档存储:(类JSON数据模式简单⽽强⼤)。
◆⾼效的传统存储⽅式:⽀持⼆进制数据及⼤型对象(如照⽚和视频)。
◆复制及⾃动故障转移:Mongo数据库⽀持服务器之间的数据复制,⽀持主-从模式及服务器之间的相互复制。
◆Auto-Sharding⾃动分⽚⽀持云级扩展性(处于早期alpha阶段):⾃动分⽚功能⽀持⽔平的数据库集群,可动态添加额外的机器。
◆动态查询:它⽀持丰富的查询表达式。
查询指令使⽤JSON形式的标记,可轻易查询⽂档中内嵌的对象及数组。
◆全索引⽀持:包括⽂档内嵌对象及数组。
Mongo的查询优化器会分析查询表达式,并⽣成⼀个⾼效的查询计划。
【MongoDB配置篇】MongoDB配置⽂件详解⽬录MongoDB实例的运⾏离不开相应的参数配置,⽐如对数据库存放路径dbpath的配置,对于参数的配置,可以在命令⾏以选项的形式进⾏配置,也可以将配置信息列⼊配置⽂件进⾏配置。
但是,使⽤配置⽂件将会使对mongod和mongos的管理变得更加容易,本篇将会对配置⽂件进⾏详细的讲解。
1 数据库环境[mongod@strong ~]$ mongod --versiondb version v4.2.0git version: a4b751dcf51dd249c5865812b390cfd1c0129c30OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013allocator: tcmallocmodules: nonebuild environment:distmod: rhel62distarch: x86_64target_arch: x86_642 配置⽂件2.1 配置⽂件格式MongoDB配置⽂件使⽤YAML的格式。
2.2 配置⽂件的使⽤对于配置⽂件的使⽤,在mongod或mongos中指定--config或-f选项。
1)指定--config选项[mongod@strong ~]$ mongod --config /etc/f2)指定-f选项[mongod@strong ~]$ mongod -f /etc/f3 配置⽂件核⼼选项3.1 systemLog选项1)选项systemLog:verbosity: <int>quiet: <boolean>traceAllExceptions: <boolean>syslogFacility: <string>path: <string>logAppend: <boolean>logRotate: <string>destination: <string>timeStampFormat: <string>component:accessControl:verbosity: <int>command:verbosity: <int># COMMENT additional component verbosity settings omitted for brevity2)说明verbosity:默认为0,值范围为0-5,⽤于输出⽇志信息的级别,值越⼤,输出的信息越多;quiet:mongod或mongos运⾏的模式,在该模式下限制输出的信息,不推荐使⽤该模式;traceAllExceptions:打印详细信息以便进⾏调试;path:⽇志⽂件的路径,mongod或mongos会将所有诊断⽇志信息发送到该位置,⽽不是标准输出或主机的syslog上;logAppend:默认为false,若设为true,当mongod或mongos实例启动时,会将新的条⽬追加到已存在的⽇志⽂件,否则,mongod会备份已存在的⽇志,并创建新的⽇志⽂件;destination:指定⽇志输出的⽬的地,具体值为file或syslog,若设置为file,需指定path,该选项未指定,则将所有⽇志输出到标准输出;timeStampFormat:⽇志信息中的时间格式,默认为iso8601-local,该选项有三个值,分别为ctime、iso8601-utc和iso8601-local;3.2 processManagement选项1)选项processManagement:fork: <boolean>pidFilePath: <string>timeZoneInfo: <string>2)说明fork:默认值为false,设置为true,会激活守护进程在后台运⾏mongod或mongos进程;pidFilePath:指定mongod或mongos写PID⽂件的路径,不指定该值,则不会创建PID⽂件;3.3 cloud选项1)选项cloud:monitoring:free:state: <string>tags: <string>2)说明state:激活或禁⽤免费的MongoDB Cloud监控,该选项有以下三个值,分别为runtime、on和off,默认为runtime;在运⾏时可以通过db.enableFreeMonitoring()和db.disableFreeMonitoring()tags:描述环境上下⽂的可选标记;3.4 net选项1)选项net:port: <int>bindIp: <string>bindIpAll: <boolean>maxIncomingConnections: <int>wireObjectCheck: <boolean>ipv6: <boolean>unixDomainSocket:enabled: <boolean>pathPrefix: <string>filePermissions: <int>tls:certificateSelector: <string>clusterCertificateSelector: <string>mode: <string>certificateKeyFile: <string>certificateKeyFilePassword: <string>clusterFile: <string>clusterPassword: <string>CAFile: <string>clusterCAFile: <string>CRLFile: <string>allowConnectionsWithoutCertificates: <boolean>allowInvalidCertificates: <boolean>allowInvalidHostnames: <boolean>disabledProtocols: <string>FIPSMode: <boolean>compression:compressors: <string>serviceExecutor: <string>2)说明port:MongoDB实例监听客户端连接的TCP端⼝,对于mongod或mongos实例,默认端⼝为27017,对于分⽚成员,默认端⼝为27018,对于配置服务器成员,默认端⼝为27019;bindIp:默认值为localhost。
User ManualContents1.SAFETY MATTERS (3)2.OVERVIEW (4)3.INTRODUCTION (5)3.1.P RODUCT OVERVIEW (5)3.2.A BOUT K EYBOARD (5)3.3.I NTRODUCTION TOUCHPAD T OUCH P AD ICON (6)3.4.L ASER H EAD D ESCRIPTION (6)3.5.W IRELESS 2.4G RECEIVER 2.4G A DAPTER ICON (7)4.STARTED (7)4.1.C ONNECT RECEIVER (7)4.2.P ROCESS OF USE (7)4.3.H OW TO CONTROL THE BACKLIT (7)4.4.E QUIPMENT SLEEP AND WAKE-UP OPERATION (7)4.5.S WITCH OFF THE DEVICE AFTER USE (7)4.6.B ATTERY C HARGING (8)5.BASIC FUNCTIONS (8)5.1.P RIMARY K EY BITS (8)5.2.SUB-KEYS (8)5.3.DEPLICATE KEYS (8)5.4.BACKLIT CONTROL KEY (8)5.5.T OUCH P AD (8)5.6.L ASER P OINTER (9)5.7.RF MATCHING (9)6.APPENDIX (9)6.1.T ECHNICAL PARAMETERS (9)6.2.M AINTENANCE (9)6.3.T ROUBLESHOOTING (11)6.4.P ACKING LIST (11)1. Safety MattersSafety MattersTo avoid injury, death of personnel or damage to the equipment the operator must refer to anexplanation in the User’s Manual.Battery: There is a piece of lithium-ion rechargeable battery in this device. Don’t water this device, or take it in the humid environment for long time, or the device will be damaged.Attention to traffic safety(CAR PC): Do not use the device while driving. If you want to use, please park the car.错误!未指定书签。
MongoDB_使用手册-中文版MongoDB 使用手册-中文版1:简介1.1 MongoDB 简介1.2 MongoDB 的优势1.3 安装 MongoDB1.4 启动和关闭 MongoDB2:数据库操作2.1 创建数据库2.2 切换数据库2.3 删除数据库2.4 数据库的备份和还原2.5 数据库的访问控制3:集合操作3.1 创建集合3.2 删除集合3.3 查找集合3.4 更新集合3.5 排序和限制集合结果4:文档操作4.1 插入文档4.2 查询文档4.3 更新文档4.4 删除文档4.5 索引和性能优化5:聚合操作5.1 聚合管道5.2 查询优化技巧5.3 数据分析和处理6:数据备份和恢复6.1 数据备份策略6.2 数据恢复方法7:复制和分片7.1 复制集7.2 分片集群8:安全性和权限控制8.1 认证和授权8.2 数据加密8.3 安全配置建议9: MongoDB 驱动程序9.1 Python 驱动程序 9.2 Java 驱动程序9.3 Node:js 驱动程序 9.4 :NET 驱动程序10:性能调优10:1 集合级别的优化 10:2 查询优化10:3 索引优化10:4 内存和磁盘配置11:故障排除11.1 常见问题11.2 日志分析11.3 性能监控12: MongoDB 与关系型数据库的比较12.1 数据模型比较12.2 查询语言比较12.3 事务和一致性比较本文档涉及附件:1:示例代码文件:[附件1](附件1:zip)2:配置文件示例:[附件2](附件2:txt)本文所涉及的法律名词及注释:1:认证和授权:指通过身份验证和权限控制来确保只有经过授权的用户才能访问和操作数据库的过程。
2:数据加密:指使用加密算法对数据库中的敏感数据进行加密保护的过程。
3:复制集:指一组 MongoDB 服务器的集合,其中包含主服务器(primary)和多个副本服务器(secondary),用于提供数据冗余和高可用性支持。
MongoDB Preface1.How This Book Is Organized1.Getting Started with MongoDB2.Developing with MongoDB3.Replication4.Sharding5.Application Administration6.Server Administration7.Appendixes2.Conventions Used in This Booking Code Examples4.O’Reilly Online Learning5.How to Contact UsI. Introduction to MongoDB1. Introduction1.Ease of Use2.Designed to Scale3.Rich with Features…4.…Without Sacrificing Speed5.The Philosophy2. Getting Started1.Documents2.Collections1.Dynamic Schemas2.Naming3.Databases4.Getting and Starting MongoDB5.Introduction to the MongoDB Shell1.Running the Shell2. A MongoDB Client3.Basic Operations with the Shell6.Data Types1.Basic Data Types2.Dates3.Arrays4.Embedded Documents5._id and ObjectIdsing the MongoDB Shell1.Tips for Using the Shell2.Running Scripts with the Shell3.Creating a .mongorc.js4.Customizing Your Prompt5.Editing Complex Variables6.Inconvenient Collection Names3. Creating, Updating, and Deleting Documents1.Inserting Documents1.insertMany2.Insert Validation3.insert2.Removing Documents1.drop3.Updating Documents1.Document Replacementing Update Operators3.Upserts4.Updating Multiple Documents5.Returning Updated Documents4. Querying1.Introduction to find1.Specifying Which Keys to Return2.Limitations2.Query Criteria1.Query Conditionals2.OR Queries3.$not3.Type-Specific Queries1.null2.Regular Expressions3.Querying Arrays4.Querying on Embedded Documents4.$where Queries5.Cursors1.Limits, Skips, and Sorts2.Avoiding Large Skips3.Immortal CursorsII. Designing Your Application5. Indexes1.Introduction to Indexes1.Creating an Index2.Introduction to Compound Indexes3.How MongoDB Selects an Indexing Compound Indexes5.How $ Operators Use Indexes6.Indexing Objects and Arrays7.Index Cardinality2.explain Output3.When Not to Index4.Types of Indexes1.Unique Indexes2.Partial Indexes5.Index Administration1.Identifying Indexes2.Changing Indexes6. Special Index and Collection Types1.Geospatial Indexes1.Types of Geospatial Queriesing Geospatial Indexespound Geospatial Indexes4.2d Indexes2.Indexes for Full Text Search1.Creating a Text Index2.Text Search3.Optimizing Full-Text Search4.Searching in Other Languages3.Capped Collections1.Creating Capped Collections2.Tailable Cursors4.Time-To-Live Indexes5.Storing Files with GridFS1.Getting Started with GridFS: mongofiles2.Working with GridFS from the MongoDB Drivers3.Under the Hood7. Introduction to the Aggregation Framework1.Pipelines, Stages, and Tunables2.Getting Started with Stages: Familiar Operations3.Expressions4.$project5.$unwind6.Array Expressions7.Accumulatorsing Accumulators in Project Stages8.Introduction to Grouping1.The _id Field in Group Stages2.Group Versus Project9.Writing Aggregation Pipeline Results to a Collection8. Transactions1.Introduction to Transactions1. A Definition of ACID2.How to Use Transactions3.Tuning Transaction Limits for Your Application1.Timing and Oplog Size Limits9. Application Design1.Schema Design Considerations1.Schema Design Patterns2.Normalization Versus Denormalization1.Examples of Data Representations2.Cardinality3.Friends, Followers, and Other Inconveniences3.Optimizations for Data Manipulation1.Removing Old Data4.Planning Out Databases and Collections5.Managing Consistency6.Migrating Schemas7.Managing Schemas8.When Not to Use MongoDBIII. Replication10. Setting Up a Replica Set1.Introduction to Replication2.Setting Up a Replica Set, Part 1working Considerations4.Security Considerations5.Setting Up a Replica Set, Part 26.Observing Replication7.Changing Your Replica Set Configuration8.How to Design a Set1.How Elections Work9.Member Configuration Options1.Priority2.Hidden Members3.Election Arbiters4.Building Indexes11. Components of a Replica Set1.Syncing1.Initial Sync2.Replication3.Handling Staleness2.Heartbeats1.Member States3.Elections4.Rollbacks1.When Rollbacks Fail12. Connecting to a Replica Set from Your Application1.Client−to−Rep lica Set Connection Behavior2.Waiting for Replication on Writes1.Other Options for “w”3.Custom Replication Guarantees1.Guaranteeing One Server per Data Center2.Guaranteeing a Majority of Nonhidden Members3.Creating Other Guarantees4.Sending Reads to Secondaries1.Consistency Considerations2.Load Considerations3.Reasons to Read from Secondaries13. Administration1.Starting Members in Standalone Mode2.Replica Set Configuration1.Creating a Replica Set2.Changing Set Members3.Creating Larger Sets4.Forcing Reconfiguration3.Manipulating Member State1.Turning Primaries into Secondaries2.Preventing Elections4.Monitoring Replication1.Getting the Status2.Visualizing the Replication Graph3.Replication Loops4.Disabling Chaining5.Calculating Lag6.Resizing the Oplog7.Building Indexes8.Replication on a BudgetIV. Sharding14. Introduction to Sharding1.What Is Sharding?1.Understanding the Components of a Cluster2.Sharding on a Single-Machine Cluster15. Configuring Sharding1.When to Shard2.Starting the Servers1.Config Servers2.The mongos Processes3.Adding a Shard from a Replica Set4.Adding Capacity5.Sharding Data3.How MongoDB Tracks Cluster Data1.Chunk Ranges2.Splitting Chunks4.The Balancer5.Collations6.Change Streams16. Choosing a Shard Key1.Taking Stock of Your Usage2.Picturing Distributions1.Ascending Shard Keys2.Randomly Distributed Shard Keys3.Location-Based Shard Keys3.Shard Key Strategies1.Hashed Shard Key2.Hashed Shard Keys for GridFS3.The Firehose Strategy4.Multi-Hotspot4.Shard Key Rules and Guidelines1.Shard Key Limitations2.Shard Key Cardinality5.Controlling Data Distributioning a Cluster for Multiple Databases and Collections2.Manual Sharding17. Sharding Administration1.Seeing the Current State1.Getting a Summary with sh.status()2.Seeing Configuration Information2.Tracking Network Connections1.Getting Connection Statistics2.Limiting the Number of Connections3.Server Administration1.Adding Servers2.Changing Servers in a Shard3.Removing a Shard4.Balancing Data1.The Balancer2.Changing Chunk Size3.Moving Chunks4.Jumbo Chunks5.Refreshing ConfigurationsV. Application Administration18. Seeing What Your Application Is Doing1.Seeing the Current Operations1.Finding Problematic Operations2.Killing Operations3.False Positives4.Preventing Phantom Operationsing the System Profiler3.Calculating Sizes1.Documents2.Collections3.Databasesing mongotop and mongostat19. An Introduction to MongoDB Security1.MongoDB Authentication and Authorization1.Authentication Mechanisms2.Authorizationing x.509 Certificates to Authenticate Both Members and Clients2. A Tutorial on MongoDB Authentication and Transport Layer Encryption1.Establish a CA2.Generate and Sign Member Certificates3.Generate and Sign Client Certificates4.Bring Up the Replica Set Without Authentication and AuthorizationEnabled5.Create the Admin User6.Restart the Replica Set with Authentication and Authorization Enabled 20. Durability1.Durability at the Member Level Through Journaling2.Durability at the Cluster Level Using Write Concern1.The w and wtimeout Options for writeConcern2.The j (Journaling) Option for writeConcern3.Durability at a Cluster Level Using Read Concern4.Durability of Transactions Using a Write Concern5.What MongoDB Does Not Guarantee6.Checking for CorruptionVI. Server Administration21. Setting Up MongoDB in Production1.Starting from the Command Line1.File-Based Configuration2.Stopping MongoDB3.Security1.Data Encryption2.SSL Connections4.Logging22. Monitoring MongoDB1.Monitoring Memory Usage1.Introduction to Computer Memory2.Tracking Memory Usage3.Tracking Page Faults4.I/O Wait2.Calculating the Working Set1.Some Working Set Examples3.Tracking Performance4.Tracking Free Space5.Monitoring Replication23. Making Backups1.Backup Methods2.Backing Up a Server1.Filesystem Snapshot2.Copying Data Filesing mongodump3.Specific Considerations for Replica Sets4.Specific Considerations for Sharded Clusters1.Backing Up and Restoring an Entire Cluster2.Backing Up and Restoring a Single Shard24. Deploying MongoDB5.Designing the System1.Choosing a Storage Medium2.Recommended RAID Configurations3.CPU4.Operating System5.Swap Space6.Filesystem6.Virtualization1.Memory Overcommitting2.Mystery Memory3.Handling Network Disk I/O Issuesing Non-Networked Disks7.Configuring System Settings1.Turning Off NUMA2.Setting Readahead3.Disabling Transparent Huge Pages (THP)4.Choosing a Disk Scheduling Algorithm5.Disabling Access Time Tracking6.Modifying Limits8.Configuring Your Network9.System Housekeeping1.Synchronizing Clocks2.The OOM Killer3.Turn Off Periodic Tasks。
心之所向,所向披靡MongoDB如何批量删除集合MongoDB的Java驱动并没有提供删除集合的方法,只有单个删除方法:DB.collection.drop();一次方法调用就是一个网络通讯,那么如果需要删除多个集合,需要多次调用DB.collection.drop();造成多次网络通讯。
幸运的是,MongoDB提供了服务端脚本,可以通过以下脚本来批量删除,但我觉得MongoDB应该直接提供批量删除功能,普通开发人员并不会意识到通讯的性能开销。
1.</pre><p> </p><pre class="java" name="code">String names = ....; //要删除的集合名称2.String code = "";3.for(int i=0;i<names.length;i++)4. code += "db.getCollection('" + names[i] + "').drop();";5.db.eval(code);db.eval()方法用来执行javascript脚本。
需要注意的是eval执行比较好性能,会阻塞其他操作,所以,应区分只有一个集合的情况,不要eval。
MongoDB数据库文档说明MongoDB数据库简单介绍MongoDB是一个高性能,开源,无模式的文档型数据库,它在许多场景下可用于替代传统的关系型数据库或键/值存储模式。
MongoDB是用C++开发,提供了以下功能:面向集合的存储:适合存储对象及JSON形式的数据。
动态查询:Mongo支持丰富的查询表达式。
查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
完整的索引支持:包括文档内嵌对象及数组。
Mongo的查询优化器会分析查询表达式,并生成一个高效的查询计划。
mongodb操作手册MongoDB是一种流行的文档型数据库,逐渐成为许多公司的首选。
但是,操作MongDB可能对新手来说有些棘手。
下面将为你提供MongoDB操作手册,以帮助你更高效地操作MongoDB。
1. 安装MongoDB首先,你需要安装MongoDB。
在MongoDB官网下载传递给操作系统的安装包(Windows、Linux或Mac OS),然后按照安装向导完成安装。
2. 启动MongoDB一旦安装完成,你便可以启动MongoDB。
在命令行中输入mongod 命令,这将启动MongoDB服务。
mongodb://localhost:27017是默认的MongoDB连接字符串。
这将启动默认的MongoDB实例,并连接到localhost上的端口27017。
3. 创建数据库当你成功启动MongoDB服务之后,你可以创建你的数据库。
使用MongoDB的命令createDatabase()可以轻松创建一个新的数据库。
只需在命令行中输入以下命令:> use mydatabasemydatabase是你所创建的数据库名称。
4. 插入数据在创建数据库之后,你可以开始向数据库中插入数据。
使用insert()命令,可以将数据插入到指定的集合中。
如下所示:> db.myCollection.insert( { name: "Tom", age: 25 } )这将在myCollection集合中插入一条数据。
注意,如果指定的集合还不存在,MongoDB会自动创建该集合。
5. 查询数据当你插入了许多数据之后,你可能需要查询数据。
使用find()命令,可以查找指定集合中的数据。
如下所示:> db.myCollection.find()这将为你提供myCollection集合中的所有文档。
你也可以使用过滤器,如下所示:> db.myCollection.find( { name: "Tom" } )这将为你提供名称为Tom的所有文档。
MongoDB使用说明手册目录第1章MONGODB简介 (4)1.1功能特点 (4)1.2适用范围 (4)第2章MONGODB下载及安装 (5)2.1下载地址 (5)2.2安装方法 (5)第3章MONGODB语法 (6)3.1基本命令 (6)3.1.1.启动mongodb (6)3.1.2.停止mongodb (6)3.2SQL语法 (7)3.2.1.基本操作 (7)3.2.2.数据集操作 (8)第4章JAVA操作MONGODB (10)4.1正在整理中....................................................................................................... 错误!未定义书签。
第5章其它 (10)5.1正在整理中 (20)第1章MongoDB简介1.1功能特点官方网址:/MongoDB是一个基于分布式文件存储的数据库开源项目。
由C++语言编写,旨在为WEB应用提供可护展的高性能数据存储解决方案。
它的特点是可扩展,高性能,易使用,模式自由,存储数据非常方便等,主要功能特性有:◆面向文档存储:(类JSON数据模式简单而强大)。
◆高效的传统存储方式:支持二进制数据及大型对象(如照片和视频)。
◆复制及自动故障转移:Mongo数据库支持服务器之间的数据复制,支持主-从模式及服务器之间的相互复制。
◆Auto-Sharding自动分片支持云级扩展性(处于早期alpha阶段):自动分片功能支持水平的数据库集群,可动态添加额外的机器。
◆动态查询:它支持丰富的查询表达式。
查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
◆全索引支持:包括文档内嵌对象及数组。
Mongo的查询优化器会分析查询表达式,并生成一个高效的查询计划。
◆支持RUBY,PYTHON,JA V A,C++,PHP等多种语言。
1.2适用范围适用场景:◆适合实时的插入,更新与查询,并具备应用程序实时数据存储所需的复制及高度伸缩性。
◆适合作为信息基础设施的持久化缓存层。
◆适合由数十或数百台服务器组成的数据库。
因为Mongo已经包含对MapReduce引擎的内置支持。
◆Mongo的BSON数据格式非常适合文档化格式的存储及查询。
不适用场景:◆高度事务性的系统。
◆传统的商业智能应用。
◆级为复杂的SQL查询。
第2章MongoDB下载及安装2.1下载地址/downloads选择一个稳定的版本v1.4.5,如下图:2.2安装方法通过mongod –install命令把mongodb注册成为window service。
1)创建数据库存储目录;例如:d:\data\db2)通过命令行执行:d:\data\logs,以及添加方式记录。
数据目录为d:\data\db。
并且每个数据库将储存在一个单独的目录(--directoryperdb)】安装成功后,如下图:3)启动服务后,尝试是否可用,通过命令行进入%MONGODB_HOME%\bin下执行mongo.exe命令后出现如下图所示信息表示连接成功:第3章MongoDB语法3.1基本命令3.1.1.启动mongodbrun 直接启动:例如:mongod run--dbpath 指定存储目录启动:例如:mongod –dbpath = d:\ db--port 指定端口启动:(默认端口是:27017) 例如:mongod --port 12345。
3.1.2.停止mongodb在窗口模式中,可以直接使用Ctrl+C停止服务。
3.2SQL语法3.2.1.基本操作db.AddUser(username,password) 添加用户db.auth(usrename,password) 设置数据库连接验证db.cloneDataBase(fromhost) 从目标服务器克隆一个数据库mandHelp(name) returns the help for the commanddb.copyDatabase(fromdb,todb,fromhost) 复制数据库fromdb---源数据库名称,todb---目标数据库名称,fromhost---源数据库服务器地址db.createCollection(name,{size:3333,capped:333,max:88888}) 创建一个数据集,相当于一个表db.currentOp() 取消当前库的当前操作db.dropDataBase() 删除当前数据库db.eval(func,args) run code server-sidedb.getCollection(cname) 取得一个数据集合,同用法:db['cname'] or db.getCollenctionNames() 取得所有数据集合的名称列表db.getLastError() 返回最后一个错误的提示消息db.getLastErrorObj() 返回最后一个错误的对象db.getMongo() 取得当前服务器的连接对象get the serverdb.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr of a replica pairdb.getName() 返回当操作数据库的名称db.getPrevError() 返回上一个错误对象db.getProfilingLevel()db.getReplicationInfo() 获得重复的数据db.getSisterDB(name) get the db at the same server as this onew db.killOp() 停止(杀死)在当前库的当前操作db.printCollectionStats() 返回当前库的数据集状态db.printReplicationInfo()db.printSlaveReplicationInfo()db.printShardingStatus() 返回当前数据库是否为共享数据库db.removeUser(username) 删除用户db.repairDatabase() 修复当前数据库db.resetError()db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}db.setProfilingLevel(level) 0=off,1=slow,2=alldb.shutdownServer() 关闭当前服务程序db.version() 返回当前程序的版本信息3.2.2.数据集(表)操作db.test.find({id:10}) 返回test数据集ID=10的数据集db.test.find({id:10}).count() 返回test数据集ID=10的数据总数db.test.find({id:10}).limit(2) 返回test数据集ID=10的数据集从第二条开始的数据集db.test.find({id:10}).skip(8) 返回test数据集ID=10的数据集从0到第八条的数据集db.test.find({id:10}).limit(2).skip(8) 返回test数据集ID=1=的数据集从第二条到第八条的数据db.test.find({id:10}).sort() 返回test数据集ID=10的排序数据集db.test.findOne([query]) 返回符合条件的一条数据db.test.getDB() 返回此数据集所属的数据库名称db.test.getIndexes() 返回些数据集的索引信息db.test.group({key:...,initial:...,reduce:...[,cond:...]})db.test.mapReduce(mayFunction,reduceFunction,<optional params>)db.test.remove(query) 在数据集中删除一条数据db.test.renameCollection(newName) 重命名些数据集名称db.test.save(obj) 往数据集中插入一条数据db.test.stats() 返回此数据集的状态db.test.storageSize() 返回此数据集的存储大小db.test.totalIndexSize() 返回此数据集的索引文件大小db.test.totalSize() 返回些数据集的总大小db.test.update(query,object[,upsert_bool]) 在此数据集中更新一条数据db.test.validate() 验证此数据集db.test.getShardVersion() 返回数据集共享版本号MongoDB语法与现有关系型数据库SQL语法比较MongoDB语法 MySql语法db.test.find({'name':'foobar'}) <==> select * from test where name='foobar'db.test.find() <==> select * from testdb.test.find({'ID':10}).count() <==> select count(*) from test where ID=10db.test.find().skip(10).limit(20) <==> select * from test limit 10,20db.test.find({'ID':{$in:[25,35,45]}}) <==> select * from test where ID in (25,35,45)db.test.find().sort({'ID':-1}) <==> select * from test order by ID descdb.test.distinct('name',{'ID':{$lt:20}}) <==> select distinct(name) from test where ID<20db.test.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+= obj.marks;},initial:{msum:0}}) <==> select name,sum(marks) from test group by namedb.test.find('this.ID<20',{name:1}) <==> select name from test where ID<20db.test.insert({'name':'foobar','age':25})<==>insert into test ('name','age') values('foobar',25)db.test.remove({}) <==> delete * from testdb.test.remove({'age':20}) <==> delete test where age=20db.test.remove({'age':{$lt:20}}) <==> elete test where age<20db.test.remove({'age':{$lte:20}}) <==> delete test where age<=20db.test.remove({'age':{$gt:20}}) <==> delete test where age>20db.test.remove({'age':{$gte:20}}) <==> delete test where age>=20db.test.remove({'age':{$ne:20}}) <==> delete test where age!=20db.test.update({'name':'foobar'},{$set:{'age':36}}) <==> update test set age=36 where name='foobar'db.test.update({'name':'foobar'},{$inc:{'age':3}}) <==> update test set age=age+3 where第4章JAVA操作MongoDB4.1.1.MongoDB 入门文章分类:数据库有关于MongoDB的资料现在较少,且大多为英文网站,以上内容大多由笔者翻译自官网,请翻译或理解错误之处请指证。