├── .gitignore ├── LICENSE ├── README.md ├── SUMMARY.md ├── admin ├── README.md └── prod-notes.md ├── aggregation ├── README.md └── pipeline.md ├── crud ├── README.md └── insert.md ├── data-models ├── README.md └── validation.md ├── faq ├── README.md └── fundamentals.md ├── geo-queries ├── README.md └── example.md ├── indexes └── single-field.md ├── introduction ├── README.md ├── bson.md ├── capped-col.md ├── comparison-sort-order.md ├── db-and-collections.md ├── document.md ├── extended-json.md ├── getting-started.md └── views.md ├── reference ├── collation.md ├── db-cmd │ └── README.md ├── glossary.md ├── operators │ └── query-and-project.md └── write-protocol.md ├── replication ├── README.md ├── member │ ├── README.md │ ├── arbiter.md │ ├── primary.md │ └── secondary │ │ ├── delayed.md │ │ ├── hidden.md │ │ └── priority.md └── op-log.md ├── security └── README.md ├── sharding ├── README.md ├── keys.md └── zone.md ├── shell ├── README.md └── configure.md └── text-search ├── README.md └── indexes.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Node rules: 2 | ## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 3 | .grunt 4 | 5 | ## Dependency directory 6 | ## Commenting this out is preferred by some people, see 7 | ## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git 8 | node_modules 9 | 10 | # Book build output 11 | _book 12 | 13 | # eBook build output 14 | *.epub 15 | *.mobi 16 | *.pdf 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Lellansin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mongodb 中文手册 2 | 3 | Mongodb 官方手册 v3.4 中文版翻译。 4 | 5 | ## Join us 6 | 7 | 安装 gitbook: 8 | 9 | ``` 10 | npm i -g gitbook-cli 11 | ``` 12 | 13 | 安装好之后可以: 14 | 15 | ``` 16 | gitbook serve . 17 | ``` 18 | 19 | 在本地编写并预览。 20 | 21 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [README](README.md) 4 | * [简介](introduction/README.md) 5 | * [开始使用](introduction/getting-started.md) 6 | * [数据库 & 集合](introduction/db-and-collections.md) 7 | * [视图](introduction/views.md) 8 | * [封顶集合](introduction/capped-col.md) 9 | * [文档](introduction/document.md) 10 | * [BSON 类型](introduction/bson.md) 11 | * [比较/排序命令](introduction/comparison-sort-order.md) 12 | * [MongoDB 拓展 JSON](introduction/extended-json.md) 13 | * [Shell 工具](shell/README.md) 14 | * [配置](shell/configure.md) 15 | * [增删改查](crud/README.md) 16 | * [插入](crud/insert.md) 17 | * [聚合](aggregation/README.md) 18 | * [Pipeline](aggregation/pipeline.md) 19 | * [文本搜索](text-search/README.md) 20 | * [文本索引](text-search/indexes.md) 21 | * [地理查询](geo-queries/README.md) 22 | * [通过地理位置查找餐厅](geo-queries/example.md) 23 | * [数据模型](data-models/README.md) 24 | * [文档验证](data-models/validation.md) 25 | * [Admin](admin/README.md) 26 | * [生产事项](admin/prod-notes.md) 27 | * 索引 28 | * [单字段索引](indexes/single-field.md) 29 | * 混合索引 30 | * [安全](security/README.md) 31 | * checklist 32 | * [Replication](replication/README.md) 33 | * [Members](replication/member/README.md) 34 | * [主节点](replication/member/primary.md) 35 | * 从节点 36 | * [优先节点](replication/member/secondary/priority.md) 37 | * [隐藏节点](replication/member/secondary/hidden.md) 38 | * [延迟节点](replication/member/secondary/delayed.md) 39 | * [仲裁节点](replication/member/arbiter.md) 40 | * [Oplog](replication/op-log.md) 41 | * [Sharding](sharding/README.md) 42 | * [Shard Keys](sharding/keys.md) 43 | * FAQ 44 | * [MongoDB 基本问题](faq/fundamentals.md) 45 | * 引用 46 | * 操作符 47 | * [查询过滤操作符](reference/operators/query-and-project.md) 48 | * [数据库命令](reference/db-cmd/README.md) 49 | * mongo Shell 方法 50 | * MongoDB Package 组件 51 | * 配置文件选项 52 | * MongoDB Server 参数 53 | * MongoDB 限制和吞吐 54 | * Explain Results 55 | * 系统集合 56 | * 连接字符串 URI 格式 57 | * [核对](reference/collation.md) 58 | * [MongoDB 写协议](reference/write-protocol.md) 59 | * 日志消息 60 | * 退出码和状态 61 | * [术语表](reference/glossary.md) 62 | * 默认 MongoDB 端口 63 | 64 | -------------------------------------------------------------------------------- /admin/README.md: -------------------------------------------------------------------------------- 1 | # Administration 2 | 3 | The administration documentation addresses the ongoing operation and maintenance of MongoDB instances and deployments. This documentation includes both high level overviews of these concerns as well as tutorials that cover specific procedures and processes for operating MongoDB. 4 | 5 | SEE ALSO 6 | 7 | The MongoDB Manual contains administrative documentation and tutorials thoughout several sections. See [Replica Set Tutorials](https://docs.mongodb.com/manual/administration/replica-sets/) and [Sharding](https://docs.mongodb.com/manual/sharding/) for additional tutorials and information. 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /aggregation/README.md: -------------------------------------------------------------------------------- 1 | # Aggregation 2 | 3 | On this page 4 | 5 | * [Aggregation Pipeline](https://docs.mongodb.com/manual/aggregation/#aggregation-pipeline) 6 | * [Map-Reduce](https://docs.mongodb.com/manual/aggregation/#map-reduce) 7 | * [Single Purpose Aggregation Operations](https://docs.mongodb.com/manual/aggregation/#single-purpose-aggregation-operations) 8 | * [Additional Features and Behaviors](https://docs.mongodb.com/manual/aggregation/#additional-features-and-behaviors) 9 | * [Additional Resources](https://docs.mongodb.com/manual/aggregation/#additional-resources) 10 | 11 | Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation: the[aggregation pipeline](https://docs.mongodb.com/manual/aggregation/#aggregation-framework), the[map-reduce function](https://docs.mongodb.com/manual/aggregation/#aggregation-map-reduce), and[single purpose aggregation methods](https://docs.mongodb.com/manual/aggregation/#single-purpose-agg-operations). 12 | 13 | ## Aggregation Pipeline 14 | 15 | MongoDB’s[aggregation framework](https://docs.mongodb.com/manual/core/aggregation-pipeline/)is modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into an aggregated result. 16 | 17 | The most basic pipeline stages provide_filters_that operate like queries and_document transformations_that modify the form of the output document. 18 | 19 | Other pipeline operations provide tools for grouping and sorting documents by specific field or fields as well as tools for aggregating the contents of arrays, including arrays of documents. In addition, pipeline stages can use[operators](https://docs.mongodb.com/manual/reference/operator/aggregation/#aggregation-expression-operators)for tasks such as calculating the average or concatenating a string. 20 | 21 | The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. 22 | 23 | The aggregation pipeline can operate on a[sharded collection](https://docs.mongodb.com/manual/sharding/). 24 | 25 | The aggregation pipeline can use indexes to improve its performance during some of its stages. In addition, the aggregation pipeline has an internal optimization phase. See[Pipeline Operators and Indexes](https://docs.mongodb.com/manual/core/aggregation-pipeline/#aggregation-pipeline-operators-and-performance)and[Aggregation Pipeline Optimization](https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/)for details. 26 | 27 | ![](https://docs.mongodb.com/manual/_images/aggregation-pipeline.bakedsvg.svg "Diagram of the annotated aggregation pipeline operation. The aggregation pipeline has two stages: \`\`$match\`\` and \`\`$group\`\`.") 28 | 29 | ## Map-Reduce 30 | 31 | MongoDB also provides[map-reduce](https://docs.mongodb.com/manual/core/map-reduce/)operations to perform aggregation. In general, map-reduce operations have two phases: a_map_stage that processes each document and_emits_one or more objects for each input document, and_reduce_phase that combines the output of the map operation. Optionally, map-reduce can have a_finalize_stage to make final modifications to the result. Like other aggregation operations, map-reduce can specify a query condition to select the input documents as well as sort and limit the results. 32 | 33 | Map-reduce uses custom JavaScript functions to perform the map and reduce operations, as well as the optional_finalize_operation. While the custom JavaScript provide great flexibility compared to the aggregation pipeline, in general, map-reduce is less efficient and more complex than the aggregation pipeline. 34 | 35 | Map-reduce can operate on a[sharded collection](https://docs.mongodb.com/manual/sharding/). Map-reduce operations can also output to a sharded collection. See[Aggregation Pipeline and Sharded Collections](https://docs.mongodb.com/manual/core/aggregation-pipeline-sharded-collections/)and[Map-Reduce and Sharded Collections](https://docs.mongodb.com/manual/core/map-reduce-sharded-collections/)for details. 36 | 37 | NOTE 38 | 39 | Starting in MongoDB 2.4, certain[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell functions and properties are inaccessible in map-reduce operations. MongoDB 2.4 also provides support for multiple JavaScript operations to run at the same time. Before MongoDB 2.4, JavaScript code executed in a single thread, raising concurrency issues for map-reduce. 40 | 41 | ![](https://docs.mongodb.com/manual/_images/map-reduce.bakedsvg.svg "Diagram of the annotated map-reduce operation.") 42 | 43 | ## Single Purpose Aggregation Operations 44 | 45 | MongoDB also provides[`db.collection.count()`](https://docs.mongodb.com/manual/reference/method/db.collection.count/#db.collection.count)and[`db.collection.distinct()`](https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#db.collection.distinct). 46 | 47 | All of these operations aggregate documents from a single collection. While these operations provide simple access to common aggregation processes, they lack the flexibility and capabilities of the aggregation pipeline and map-reduce. 48 | 49 | ![](https://docs.mongodb.com/manual/_images/distinct.bakedsvg.svg "Diagram of the annotated distinct operation.") 50 | 51 | ## Additional Features and Behaviors 52 | 53 | For a feature comparison of the aggregation pipeline, map-reduce, and the special group functionality, see[Aggregation Commands Comparison](https://docs.mongodb.com/manual/reference/aggregation-commands-comparison/). 54 | 55 | ## Additional Resources 56 | 57 | * [MongoDB Analytics: Learn Aggregation by Example: Exploratory Analytics and Visualization Using Flight Data](http://www.mongodb.com/presentations/mongodb-analytics-learn-aggregation-example-exploratory-analytics-and-visualization?jmp=docs) 58 | * [MongoDB for Time Series Data: Analyzing Time Series Data Using the Aggregation Framework and Hadoop](http://www.mongodb.com/presentations/mongodb-time-series-data-part-2-analyzing-time-series-data-using-aggregation-framework?jmp=docs) 59 | * [The Aggregation Framework](https://www.mongodb.com/presentations/aggregation-framework-0?jmp=docs) 60 | * [Webinar: Exploring the Aggregation Framework](https://www.mongodb.com/webinar/exploring-the-aggregation-framework?jmp=docs) 61 | * [Quick Reference Cards](https://www.mongodb.com/lp/misc/quick-reference-cards?jmp=docs) 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /aggregation/pipeline.md: -------------------------------------------------------------------------------- 1 | # Aggregation Pipeline 2 | 3 | On this page 4 | 5 | * [Pipeline](https://docs.mongodb.com/manual/core/aggregation-pipeline/#pipeline) 6 | * [Pipeline Expressions](https://docs.mongodb.com/manual/core/aggregation-pipeline/#pipeline-expressions) 7 | * [Aggregation Pipeline Behavior](https://docs.mongodb.com/manual/core/aggregation-pipeline/#aggregation-pipeline-behavior) 8 | * [Additional Resources](https://docs.mongodb.com/manual/core/aggregation-pipeline/#additional-resources) 9 | 10 | The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into aggregated results. 11 | 12 | ![](https://docs.mongodb.com/manual/_images/aggregation-pipeline.bakedsvg.svg "Diagram of the annotated aggregation pipeline operation. The aggregation pipeline has two stages: \`\`$match\`\` and \`\`$group\`\`.") 13 | 14 | The aggregation pipeline provides an alternative to[map-reduce](https://docs.mongodb.com/manual/reference/glossary/#term-map-reduce)and may be the preferred solution for aggregation tasks where the complexity of map-reduce may be unwarranted. 15 | 16 | Aggregation pipeline have some limitations on value types and result size. See[Aggregation Pipeline Limits](https://docs.mongodb.com/manual/core/aggregation-pipeline-limits/)for details on limits and restrictions on the aggregation pipeline. 17 | 18 | ## Pipeline 19 | 20 | The MongoDB aggregation pipeline consists of[stages](https://docs.mongodb.com/manual/reference/operator/aggregation/#aggregation-pipeline-operator-reference). Each stage transforms the documents as they pass through the pipeline. Pipeline stages do not need to produce one output document for every input document; e.g., some stages may generate new documents or filter out documents. Pipeline stages can appear multiple times in the pipeline. 21 | 22 | MongoDB provides the[`db.collection.aggregate()`](https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/#db.collection.aggregate)method in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell and the[`aggregate`](https://docs.mongodb.com/manual/reference/command/aggregate/#dbcmd.aggregate)command for aggregation pipeline. See[Stage Operators](https://docs.mongodb.com/manual/reference/operator/aggregation/#aggregation-pipeline-operator-reference)for the available stages. 23 | 24 | For example usage of the aggregation pipeline, consider[Aggregation with User Preference Data](https://docs.mongodb.com/manual/tutorial/aggregation-with-user-preference-data/)and[Aggregation with the Zip Code Data Set](https://docs.mongodb.com/manual/tutorial/aggregation-zip-code-data-set/). 25 | 26 | ## Pipeline Expressions 27 | 28 | Some pipeline stages take a pipeline expression as the operand. Pipeline expressions specify the transformation to apply to the input documents. Expressions have a[document](https://docs.mongodb.com/manual/core/document/)structure and can contain other[expression](https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions). 29 | 30 | Pipeline expressions can only operate on the current document in the pipeline and cannot refer to data from other documents: expression operations provide in-memory transformation of documents. 31 | 32 | Generally, expressions are stateless and are only evaluated when seen by the aggregation process with one exception:[accumulator](https://docs.mongodb.com/manual/reference/operator/aggregation/#aggregation-accumulator-operators)expressions. 33 | 34 | The accumulators, used in the[`$group`](https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group)stage, maintain their state \(e.g. totals, maximums, minimums, and related data\) as documents progress through the pipeline. 35 | 36 | Changed in version 3.2:Some accumulators are available in the[`$project`](https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project)stage; however, when used in the[`$project`](https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project)stage, the accumulators do not maintain their state across documents. 37 | 38 | For more information on expressions, see[Expressions](https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions). 39 | 40 | ## Aggregation Pipeline Behavior 41 | 42 | In MongoDB, the[`aggregate`](https://docs.mongodb.com/manual/reference/command/aggregate/#dbcmd.aggregate)command operates on a single collection, logically passing the_entire_collection into the aggregation pipeline. To optimize the operation, wherever possible, use the following strategies to avoid scanning the entire collection. 43 | 44 | ### Pipeline Operators and Indexes 45 | 46 | The[`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match)and[`$sort`](https://docs.mongodb.com/manual/reference/operator/aggregation/sort/#pipe._S_sort)pipeline operators can take advantage of an index when they occur at the**beginning**of the pipeline. 47 | 48 | New in version 2.4:The[`$geoNear`](https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear)pipeline operator takes advantage of a geospatial index. When using[`$geoNear`](https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear), the[`$geoNear`](https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear)pipeline operation must appear as the first stage in an aggregation pipeline. 49 | 50 | Changed in version 3.2:Starting in MongoDB 3.2, indexes can[cover](https://docs.mongodb.com/manual/core/query-optimization/#read-operations-covered-query)an aggregation pipeline. In MongoDB 2.6 and 3.0, indexes could not cover an aggregation pipeline since even when the pipeline uses an index, aggregation still requires access to the actual documents. 51 | 52 | ### Early Filtering 53 | 54 | If your aggregation operation requires only a subset of the data in a collection, use the[`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match),[`$limit`](https://docs.mongodb.com/manual/reference/operator/aggregation/limit/#pipe._S_limit), and[`$skip`](https://docs.mongodb.com/manual/reference/operator/aggregation/skip/#pipe._S_skip)stages to restrict the documents that enter at the beginning of the pipeline. When placed at the beginning of a pipeline,[`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match)operations use suitable indexes to scan only the matching documents in a collection. 55 | 56 | Placing a[`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match)pipeline stage followed by a[`$sort`](https://docs.mongodb.com/manual/reference/operator/aggregation/sort/#pipe._S_sort)stage at the start of the pipeline is logically equivalent to a single query with a sort and can use an index. When possible, place[`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match)operators at the beginning of the pipeline. 57 | 58 | ### Additional Features 59 | 60 | The aggregation pipeline has an internal optimization phase that provides improved performance for certain sequences of operators. For details, see[Aggregation Pipeline Optimization](https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/). 61 | 62 | The aggregation pipeline supports operations on sharded collections. See[Aggregation Pipeline and Sharded Collections](https://docs.mongodb.com/manual/core/aggregation-pipeline-sharded-collections/#aggregation-pipeline-sharded-collection). 63 | 64 | ## Additional Resources 65 | 66 | * [MongoDB Analytics: Learn Aggregation by Example: Exploratory Analytics and Visualization Using Flight Data](http://www.mongodb.com/presentations/mongodb-analytics-learn-aggregation-example-exploratory-analytics-and-visualization?jmp=docs) 67 | * [MongoDB for Time Series Data: Analyzing Time Series Data Using the Aggregation Framework and Hadoop](http://www.mongodb.com/presentations/mongodb-time-series-data-part-2-analyzing-time-series-data-using-aggregation-framework?jmp=docs) 68 | * [The Aggregation Framework](https://www.mongodb.com/presentations/aggregation-framework-0?jmp=docs) 69 | * [Webinar: Exploring the Aggregation Framework](https://www.mongodb.com/webinar/exploring-the-aggregation-framework?jmp=docs) 70 | * [Quick Reference Cards](https://www.mongodb.com/lp/misc/quick-reference-cards?jmp=docs) 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /crud/README.md: -------------------------------------------------------------------------------- 1 | # MongoDB CRUD Operations 2 | 3 | On this page 4 | 5 | * [Create Operations](https://docs.mongodb.com/manual/crud/#create-operations) 6 | * [Read Operations](https://docs.mongodb.com/manual/crud/#read-operations) 7 | * [Update Operations](https://docs.mongodb.com/manual/crud/#update-operations) 8 | * [Delete Operations](https://docs.mongodb.com/manual/crud/#delete-operations) 9 | * [Bulk Write](https://docs.mongodb.com/manual/crud/#bulk-write) 10 | 11 | CRUD operations_create_,_read_,_update_, and_delete_[documents](https://docs.mongodb.com/manual/core/document/#bson-document-format). 12 | 13 | ## Create Operations 14 | 15 | Create or insert operations add new[documents](https://docs.mongodb.com/manual/core/document/#bson-document-format)to a[collection](https://docs.mongodb.com/manual/core/databases-and-collections/#collections). If the collection does not currently exist, insert operations will create the collection. 16 | 17 | MongoDB provides the following methods to insert documents into a collection: 18 | 19 | * [`db.collection.insertOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne) 20 | _New in version 3.2_ 21 | * [`db.collection.insertMany()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#db.collection.insertMany) 22 | _New in version 3.2_ 23 | 24 | In MongoDB, insert operations target a single[collection](https://docs.mongodb.com/manual/reference/glossary/#term-collection). All write operations in MongoDB are[atomic](https://docs.mongodb.com/manual/core/write-operations-atomicity/)on the level of a single[document](https://docs.mongodb.com/manual/core/document/). 25 | 26 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-mongodb-insertOne.bakedsvg.svg "The components of a MongoDB insertOne operations.") 27 | 28 | For examples, see[Insert Documents](https://docs.mongodb.com/manual/tutorial/insert-documents/). 29 | 30 | ## Read Operations 31 | 32 | Read operations retrieves[documents](https://docs.mongodb.com/manual/core/document/#bson-document-format)from a[collection](https://docs.mongodb.com/manual/core/databases-and-collections/#collections); i.e. queries a collection for documents. MongoDB provides the following methods to read documents from a collection: 33 | 34 | * [`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find) 35 | 36 | You can specify[query filters or criteria](https://docs.mongodb.com/manual/tutorial/query-documents/#read-operations-query-argument)that identify the documents to return. 37 | 38 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-mongodb-find.bakedsvg.svg "The components of a MongoDB find operation.") 39 | 40 | For examples, see: 41 | 42 | * [Query Documents](https://docs.mongodb.com/manual/tutorial/query-documents/) 43 | * [Query on Embedded/Nested Documents](https://docs.mongodb.com/manual/tutorial/query-embedded-documents/) 44 | * [Query an Array](https://docs.mongodb.com/manual/tutorial/query-arrays/) 45 | * [Query an Array of Embedded Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) 46 | 47 | ## Update Operations 48 | 49 | Update operations modify existing[documents](https://docs.mongodb.com/manual/core/document/#bson-document-format)in a[collection](https://docs.mongodb.com/manual/core/databases-and-collections/#collections). MongoDB provides the following methods to update documents of a collection: 50 | 51 | * [`db.collection.updateOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#db.collection.updateOne) 52 | _New in version 3.2_ 53 | * [`db.collection.updateMany()`](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#db.collection.updateMany) 54 | _New in version 3.2_ 55 | * [`db.collection.replaceOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/#db.collection.replaceOne) 56 | _New in version 3.2_ 57 | 58 | In MongoDB, update operations target a single collection. All write operations in MongoDB are[atomic](https://docs.mongodb.com/manual/core/write-operations-atomicity/)on the level of a single document. 59 | 60 | You can specify criteria, or filters, that identify the documents to update. These[filters](https://docs.mongodb.com/manual/core/document/#document-query-filter)use the same syntax as read operations. 61 | 62 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-mongodb-updateMany.bakedsvg.svg "The components of a MongoDB updateMany operation.") 63 | 64 | For examples, see[Update Documents](https://docs.mongodb.com/manual/tutorial/update-documents/). 65 | 66 | ## Delete Operations 67 | 68 | Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection: 69 | 70 | * [`db.collection.deleteOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/#db.collection.deleteOne) 71 | _New in version 3.2_ 72 | * [`db.collection.deleteMany()`](https://docs.mongodb.com/manual/reference/method/db.collection.deleteMany/#db.collection.deleteMany) 73 | _New in version 3.2_ 74 | 75 | In MongoDB, delete operations target a single[collection](https://docs.mongodb.com/manual/reference/glossary/#term-collection). All write operations in MongoDB are[atomic](https://docs.mongodb.com/manual/core/write-operations-atomicity/)on the level of a single document. 76 | 77 | You can specify criteria, or filters, that identify the documents to remove. These[filters](https://docs.mongodb.com/manual/core/document/#document-query-filter)use the same syntax as read operations. 78 | 79 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-mongodb-deleteMany.bakedsvg.svg "The components of a MongoDB deleteMany operation.") 80 | 81 | For examples, see[Delete Documents](https://docs.mongodb.com/manual/tutorial/remove-documents/). 82 | 83 | ## Bulk Write 84 | 85 | MongoDB provides the ability to perform write operations in bulk. For details, see[Bulk Write Operations](https://docs.mongodb.com/manual/core/bulk-write-operations/). 86 | 87 | -------------------------------------------------------------------------------- /crud/insert.md: -------------------------------------------------------------------------------- 1 | # Insert Documents 2 | 3 | This page provides examples of insert operations in MongoDB. 4 | 5 | > CREATING A COLLECTION 6 | > 7 | > If the collection does not currently exist, insert operations will create the collection. 8 | 9 | ## Insert a Single Document 10 | 11 | New in version 3.2. 12 | 13 | [Collection.insertOne\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertOne)inserts a_single_[document](https://docs.mongodb.com/manual/core/document/#bson-document-format)into a collection. 14 | 15 | The following example inserts a new document into the`inventory`collection. If the document does not specify an`_id`field, the Node.js driver adds the`_id`field with an ObjectId value to the new document. See[Insert Behavior](https://docs.mongodb.com/manual/tutorial/insert-documents/#write-op-insert-behavior). 16 | 17 | ```js 18 | db.collection('inventory').insertOne({ 19 | item: "canvas", 20 | qty: 100, 21 | tags: ["cotton"], 22 | size: { h: 28, w: 35.5, uom: "cm" } 23 | }) 24 | .then(function(result) { 25 | // process result 26 | }) 27 | ``` 28 | 29 | [insertOne\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertOne)returns a promise that provides a`result`. The`result.insertedId`promise contains the`_id`of the newly inserted document. 30 | 31 | To retrieve the document that you just inserted,[query the collection](https://docs.mongodb.com/manual/core/document/#document-query-filter): 32 | 33 | ```js 34 | var cursor = db.collection('inventory').find({ 35 | item: "canvas", 36 | }); 37 | ``` 38 | 39 | ## Insert Multiple Documents 40 | 41 | New in version 3.2. 42 | 43 | [Collection.insertMany\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany)can insert_multiple_[documents](https://docs.mongodb.com/manual/core/document/#bson-document-format)into a collection. Pass an array of documents to the method. 44 | 45 | The following example inserts three new documents into the`inventory`collection. If the documents do not specify an`_id`field, the Node.js driver adds the`_id`field with an ObjectId value to each document. See[Insert Behavior](https://docs.mongodb.com/manual/tutorial/insert-documents/#write-op-insert-behavior). 46 | 47 | ```js 48 | db.collection('inventory').insertMany([ 49 | { item: "journal", 50 | qty: 25, 51 | tags: ["blank", "red"], 52 | size: { h: 14, w: 21, uom: "cm" }}, 53 | { item: "mat", 54 | qty: 85, 55 | tags: ["gray"], 56 | size: { h: 27.9, w: 35.5, uom: "cm" }}, 57 | { item: "mousepad", 58 | qty: 25, 59 | tags: ["gel", "blue"], 60 | size: { h: 19, w: 22.85, uom: "cm" }} 61 | ]) 62 | .then(function(result) { 63 | // process result 64 | }) 65 | ``` 66 | 67 | [insertMany\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany)returns a promise that provides a`result`. The`result.insertedIds`field contains an array with the`_id`of each newly inserted document. 68 | 69 | To retrieve the inserted documents,[query the collection](https://docs.mongodb.com/manual/tutorial/query-documents/#read-operations-query-document): 70 | 71 | ```js 72 | var cursor = db.collection('inventory').find({}); 73 | ``` 74 | 75 | ## Insert Behavior 76 | 77 | ### Collection Creation 78 | 79 | If the collection does not currently exist, insert operations will create the collection. 80 | 81 | ### `_id`Field 82 | 83 | In MongoDB, each document stored in a collection requires a unique[\_id](https://docs.mongodb.com/manual/reference/glossary/#term-id)field that acts as a[primary key](https://docs.mongodb.com/manual/reference/glossary/#term-primary-key). If an inserted document omits the`_id`field, the MongoDB driver automatically generates an[ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid)for the`_id`field. 84 | 85 | This also applies to documents inserted through update operations with[upsert: true](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-parameter). 86 | 87 | ### Atomicity 88 | 89 | All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see[Atomicity and Transactions](https://docs.mongodb.com/manual/core/write-operations-atomicity/) 90 | 91 | ### Write Acknowledgement 92 | 93 | With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see[Write Concern](https://docs.mongodb.com/manual/reference/write-concern/). 94 | 95 | SEE ALSO 96 | 97 | * [Collection.insertOne\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertOne) 98 | * [Collection.insertMany\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) 99 | * [Additional Methods for Inserts](https://docs.mongodb.com/manual/reference/insert-methods/#additional-inserts) 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /data-models/README.md: -------------------------------------------------------------------------------- 1 | # Data Modeling Introduction 2 | 3 | On this page 4 | 5 | * [Document Structure](https://docs.mongodb.com/manual/core/data-modeling-introduction/#document-structure) 6 | * [Atomicity of Write Operations](https://docs.mongodb.com/manual/core/data-modeling-introduction/#atomicity-of-write-operations) 7 | * [Document Growth](https://docs.mongodb.com/manual/core/data-modeling-introduction/#document-growth) 8 | * [Data Use and Performance](https://docs.mongodb.com/manual/core/data-modeling-introduction/#data-use-and-performance) 9 | * [Additional Resources](https://docs.mongodb.com/manual/core/data-modeling-introduction/#additional-resources) 10 | 11 | Data in MongoDB has a_flexible schema_. Unlike SQL databases, where you must determine and declare a table’s schema before inserting data, MongoDB’s[collections](https://docs.mongodb.com/manual/reference/glossary/#term-collection)do not enforce[document](https://docs.mongodb.com/manual/reference/glossary/#term-document)structure. This flexibility facilitates the mapping of documents to an entity or an object. Each document can match the data fields of the represented entity, even if the data has substantial variation. In practice, however, the documents in a collection share a similar structure. 12 | 13 | The key challenge in data modeling is balancing the needs of the application, the performance characteristics of the database engine, and the data retrieval patterns. When designing data models, always consider the application usage of the data \(i.e. queries, updates, and processing of the data\) as well as the inherent structure of the data itself. 14 | 15 | ## Document Structure 16 | 17 | The key decision in designing data models for MongoDB applications revolves around the structure of documents and how the application represents relationships between data. There are two tools that allow applications to represent these relationships:_references_and_embedded documents_. 18 | 19 | ### References 20 | 21 | References store the relationships between data by including links or_references_from one document to another. Applications can resolve these[references](https://docs.mongodb.com/manual/reference/database-references/)to access the related data. Broadly, these are_normalized_data models. 22 | 23 | ![](https://docs.mongodb.com/manual/_images/data-model-normalized.bakedsvg.svg "Data model using references to link documents. Both the \`\`contact\`\` document and the \`\`access\`\` document contain a reference to the \`\`user\`\` document.") 24 | 25 | See[Normalized Data Models](https://docs.mongodb.com/manual/core/data-model-design/#data-modeling-referencing)for the strengths and weaknesses of using references. 26 | 27 | ### Embedded Data 28 | 29 | Embedded documents capture relationships between data by storing related data in a single document structure. MongoDB documents make it possible to embed document structures in a field or array within a document. These_denormalized_data models allow applications to retrieve and manipulate related data in a single database operation. 30 | 31 | ![](https://docs.mongodb.com/manual/_images/data-model-denormalized.bakedsvg.svg "Data model with embedded fields that contain all related information.") 32 | 33 | See[Embedded Data Models](https://docs.mongodb.com/manual/core/data-model-design/#data-modeling-embedding)for the strengths and weaknesses of embedding documents. 34 | 35 | ## Atomicity of Write Operations 36 | 37 | In MongoDB, write operations are atomic at the[document](https://docs.mongodb.com/manual/reference/glossary/#term-document)level, and no single write operation can atomically affect more than one document or more than one collection. A denormalized data model with embedded data combines all related data for a represented entity in a single document. This facilitates atomic write operations since a single write operation can insert or update the data for an entity. Normalizing the data would split the data across multiple collections and would require multiple write operations that are not atomic collectively. 38 | 39 | However, schemas that facilitate atomic writes may limit ways that applications can use the data or may limit ways to modify applications. The[Atomicity Considerations](https://docs.mongodb.com/manual/core/data-model-operations/#data-model-atomicity)documentation describes the challenge of designing a schema that balances flexibility and atomicity. 40 | 41 | ## Document Growth 42 | 43 | Some updates, such as pushing elements to an array or adding new fields, increase a[document’s](https://docs.mongodb.com/manual/reference/glossary/#term-document)size. 44 | 45 | For the MMAPv1 storage engine, if the document size exceeds the allocated space for that document, MongoDB relocates the document on disk. When using the MMAPv1 storage engine, growth consideration can affect the decision to normalize or denormalize data. See[Document Growth Considerations](https://docs.mongodb.com/manual/core/data-model-operations/#data-model-document-growth)for more about planning for and managing document growth for MMAPv1. 46 | 47 | ## Data Use and Performance 48 | 49 | When designing a data model, consider how applications will use your database. For instance, if your application only uses recently inserted documents, consider using[Capped Collections](https://docs.mongodb.com/manual/core/capped-collections/). Or if your application needs are mainly read operations to a collection, adding indexes to support common queries can improve performance. 50 | 51 | See[Operational Factors and Data Models](https://docs.mongodb.com/manual/core/data-model-operations/)for more information on these and other operational considerations that affect data model designs. 52 | 53 | ## Additional Resources 54 | 55 | * [Thinking in Documents Part 1 \(Blog Post\)](https://www.mongodb.com/blog/post/thinking-documents-part-1?jmp=docs) 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /data-models/validation.md: -------------------------------------------------------------------------------- 1 | # Document Validation 2 | 3 | On this page 4 | 5 | * [Behavior](https://docs.mongodb.com/manual/core/document-validation/#behavior) 6 | * [Restrictions](https://docs.mongodb.com/manual/core/document-validation/#restrictions) 7 | * [Bypass Document Validation](https://docs.mongodb.com/manual/core/document-validation/#bypass-document-validation) 8 | * [Additional Information](https://docs.mongodb.com/manual/core/document-validation/#additional-information) 9 | 10 | New in version 3.2. 11 | 12 | MongoDB provides the capability to validate documents during updates and insertions. Validation rules are specified on a per-collection basis using the`validator`option, which takes a document that specifies the validation rules or expressions. Specify the expressions using any[query operators](https://docs.mongodb.com/manual/reference/operator/query/#query-selectors), with the exception of[`$near`](https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near),[`$nearSphere`](https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere),[`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text), and[`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where). 13 | 14 | Add document validation to an existing collection using the[`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod)command with the`validator`option. You can also specify document validation rules when creating a new collection using[`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)with the`validator`option, as in the following: 15 | 16 | ``` 17 | db.createCollection( "contacts", 18 | { validator: { $or: 19 | [ 20 | { phone: { $type: "string" } }, 21 | { email: { $regex: /@mongodb\.com$/ } }, 22 | { status: { $in: [ "Unknown", "Incomplete" ] } } 23 | ] 24 | } 25 | } ) 26 | ``` 27 | 28 | MongoDB also provides the`validationLevel`option, which determines how strictly MongoDB applies validation rules to existing documents during an update, and the`validationAction`option, which determines whether MongoDB should`error`and reject documents that violate the validation rules or`warn`about the violations in the log but allow invalid documents. 29 | 30 | ## Behavior 31 | 32 | Validation occurs during updates and inserts. When you add validation to a collection, existing documents do not undergo validation checks until modification. 33 | 34 | ### Existing Documents 35 | 36 | You can control how MongoDB handles existing documents using the`validationLevel`option. 37 | 38 | By default,`validationLevel`is`strict`and MongoDB applies validation rules to all inserts and updates. Setting`validationLevel`to`moderate`applies validation rules to inserts and to updates to existing documents that fulfill the validation criteria. With the`moderate`level, updates to existing documents that do not fulfill the validation criteria are not checked for validity. 39 | 40 | EXAMPLE 41 | 42 | Consider the following documents in a`contacts`collection: 43 | 44 | ``` 45 | { 46 | "_id": "125876", 47 | "name": "Anne", 48 | "phone": "+1 555 123 456", 49 | "city": "London", 50 | "status": "Complete" 51 | }, 52 | { 53 | "_id": "860000", 54 | "name": "Ivan", 55 | "city": "Vancouver" 56 | } 57 | ``` 58 | 59 | Issue the following command to add a validator to the`contacts`collection: 60 | 61 | ``` 62 | db.runCommand( { 63 | collMod: "contacts", 64 | validator: { $or: [ { phone: { $exists: true } }, { email: { $exists: true } } ] }, 65 | validationLevel: "moderate" 66 | } ) 67 | ``` 68 | 69 | The`contacts`collection now has a validator with the`moderate`validationLevel. If you attempted to update the document with`_id`of`125876`, MongoDB would apply validation rules since the existing document matches the criteria. In contrast, MongoDB will not apply validation rules to updates to the document with`_id`of`860000`as it does not meet the validation rules. 70 | 71 | To disable validation entirely, you can set`validationLevel`to`off`. 72 | 73 | ### Accept or Reject Invalid Documents 74 | 75 | The`validationAction`option determines how MongoDB handles documents that violate the validation rules. 76 | 77 | By default,`validationAction`is`error`and MongoDB rejects any insertion or update that violates the validation criteria. When`validationAction`is set to`warn`, MongoDB logs any violations but allows the insertion or update to proceed. 78 | 79 | EXAMPLE 80 | 81 | The following example creates a`contacts`collection with a validator that specifies that inserted or updated documents should match at least one of three following conditions: 82 | 83 | * the 84 | `phone` 85 | field is a string 86 | * the 87 | `email` 88 | field matches the regular expression 89 | * the 90 | `status` 91 | field is either 92 | `Unknown` 93 | or 94 | `Incomplete` 95 | . 96 | 97 | ``` 98 | db.createCollection( "contacts", 99 | { 100 | validator: { $or: 101 | [ 102 | { phone: { $type: "string" } }, 103 | { email: { $regex: /@mongodb\.com$/ } }, 104 | { status: { $in: [ "Unknown", "Incomplete" ] } } 105 | ] 106 | }, 107 | validationAction: "warn" 108 | } 109 | ) 110 | ``` 111 | 112 | With the validator in place, the following insert operation fails the validation rules, but since the`validationAction`is`warn`, the write operation logs the failure and succeeds. 113 | 114 | ``` 115 | db.contacts.insert( { name: "Amanda", status: "Updated" } ) 116 | ``` 117 | 118 | The log includes the full namespace of the collection and the document that failed the validation rules, as well as the time of the operation: 119 | 120 | ``` 121 | 2015-10-15T11:20:44.260-0400 W STORAGE [conn3] Document would fail validation collection: example.contacts doc: { _id: ObjectId('561fc44c067a5d85b96274e4'), name: "Amanda", status: "Updated" } 122 | ``` 123 | 124 | ## Restrictions 125 | 126 | You cannot specify a validator for collections in the`admin`,`local`, and`config`databases. 127 | 128 | You cannot specify a validator for`system.*`collections. 129 | 130 | ## Bypass Document Validation 131 | 132 | Users can bypass document validation using the`bypassDocumentValidation`option. For a list of commands that support the`bypassDocumentValidation`option, see[Document Validation](https://docs.mongodb.com/manual/release-notes/3.2/#rel-notes-document-validation). 133 | 134 | For deployments that have enabled access control, to bypass document validation, the authenticated user must have[`bypassDocumentValidation`](https://docs.mongodb.com/manual/reference/privilege-actions/#bypassDocumentValidation)action. The built-in roles[`dbAdmin`](https://docs.mongodb.com/manual/reference/built-in-roles/#dbAdmin)and[`restore`](https://docs.mongodb.com/manual/reference/built-in-roles/#restore)provide this action. 135 | 136 | ## Additional Information 137 | 138 | SEE ALSO 139 | 140 | [`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod),[`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection),[`db.getCollectionInfos()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/#db.getCollectionInfos). 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /faq/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElemeFE/mongodb-doc-cn/c7c6e7167f498ad0a99da50af32897baa84b7f2b/faq/README.md -------------------------------------------------------------------------------- /faq/fundamentals.md: -------------------------------------------------------------------------------- 1 | # FAQ: MongoDB Fundamentals 2 | 3 | On this page 4 | 5 | * [What platforms does MongoDB support?](https://docs.mongodb.com/manual/faq/fundamentals/#what-platforms-does-mongodb-support) 6 | * [Is MongoDB offered as a hosted service?](https://docs.mongodb.com/manual/faq/fundamentals/#is-mongodb-offered-as-a-hosted-service) 7 | * [How does a collection differ from a table?](https://docs.mongodb.com/manual/faq/fundamentals/#how-does-a-collection-differ-from-a-table) 8 | * [How do I create a database and a collection?](https://docs.mongodb.com/manual/faq/fundamentals/#how-do-i-create-a-database-and-a-collection) 9 | * [How do I define or alter the collection schema?](https://docs.mongodb.com/manual/faq/fundamentals/#how-do-i-define-or-alter-the-collection-schema) 10 | * [Does MongoDB support SQL?](https://docs.mongodb.com/manual/faq/fundamentals/#does-mongodb-support-sql) 11 | * [Does MongoDB support transactions?](https://docs.mongodb.com/manual/faq/fundamentals/#does-mongodb-support-transactions) 12 | * [Does MongoDB handle caching?](https://docs.mongodb.com/manual/faq/fundamentals/#does-mongodb-handle-caching) 13 | * [How does MongoDB address SQL or Query injection?](https://docs.mongodb.com/manual/faq/fundamentals/#how-does-mongodb-address-sql-or-query-injection) 14 | 15 | This document answers some common questions about MongoDB. 16 | 17 | ## What platforms does MongoDB support? 18 | 19 | For the list of supported platforms, see[Supported Platforms](https://docs.mongodb.com/manual/administration/production-notes/#prod-notes-supported-platforms). 20 | 21 | ## Is MongoDB offered as a hosted service? 22 | 23 | Yes.[MongoDB Atlas](https://www.mongodb.com/cloud/atlas?jmp=docs)is a cloud-hosted database-as-a-service. For more information, please visit the[MongoDB Atlas docs](https://www.mongodb.com/cloud/atlas?jmp=docs). 24 | 25 | ## How does a collection differ from a table? 26 | 27 | Instead of tables, a MongoDB database stores its data in[collections](https://docs.mongodb.com/manual/reference/glossary/#term-collection). A collection holds one or more[BSON documents](https://docs.mongodb.com/manual/core/document/#bson-document-format). Documents are analogous to records or rows in a relational database table. Each document has[one or more fields](https://docs.mongodb.com/manual/core/document/#document-structure); fields are similar to the columns in a relational database table. 28 | 29 | SEE ALSO 30 | 31 | [SQL to MongoDB Mapping Chart](https://docs.mongodb.com/manual/reference/sql-comparison/),[Introduction to MongoDB](https://docs.mongodb.com/manual/introduction/) 32 | 33 | ## How do I create a database and a collection? 34 | 35 | If a database does not exist, MongoDB creates the database when you first store data for that database. 36 | 37 | If a collection does not exist, MongoDB creates the collection when you first store data for that collection.[\[1\]](https://docs.mongodb.com/manual/faq/fundamentals/#explicit-creation) 38 | 39 | As such, you can switch to a non-existent database \(`use`\) and perform the following operation: 40 | 41 | ``` 42 | use myNewDB 43 | 44 | db.myNewCollection1.insertOne( { x: 1 } ) 45 | db.myNewCollection2.createIndex( { a: 1 } ) 46 | ``` 47 | 48 | The`insert`operation creates both the database`myNewDB`and the collection`myNewCollection1`if they do not already exist. 49 | 50 | The`createIndex`operation, which occurs after the`myNewDB`has been created, creates the index and the collection`myNewCollection2`if the collection does not exist. If`myNewDb`did not exist, the`createIndex`operation would have also created the`myNewDB`. 51 | 52 | | [\[1\]](https://docs.mongodb.com/manual/faq/fundamentals/#id1) | You can also create a collection explicitly using[`db.createCollection`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)if you want to specify specific options, such as maximum size or document validation rules. | 53 | | :--- | :--- | 54 | 55 | 56 | ## How do I define or alter the collection schema? 57 | 58 | You do not need to specify a schema for a collection in MongoDB. Although it is common for the documents in a collection to have a largely homogeneous structure, it is not a requirement; i.e. documents in a single collection do not need to have the same set of fields. The data type for a field can differ across documents in a collection as well. 59 | 60 | To change the structure of the documents in a collection, update the documents to the new structure. For instance, add new fields, remove existing ones, or update the value of a field to a new type. 61 | 62 | Changed in version 3.2:Starting in MongoDB 3.2, however, you can enforce[document validation rules](https://docs.mongodb.com/manual/core/document-validation/)for a collection during update and insert operations. 63 | 64 | Some collection properties, such as specifying a maximum size, can be specified during the explicit creation of a collection and be modified. See[`db.createCollection`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)and[`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod). If you are not specifying these properties, you do not need to explicitly create the collection since MongoDB creates new collections when you first store data for the collections. 65 | 66 | ## Does MongoDB support SQL? 67 | 68 | No. However, MongoDB does support a rich query language of its own. For examples on using MongoDB’s query language, see[MongoDB CRUD Operations](https://docs.mongodb.com/manual/crud/) 69 | 70 | SEE ALSO 71 | 72 | [SQL to MongoDB Mapping Chart](https://docs.mongodb.com/manual/reference/sql-comparison/) 73 | 74 | ## Does MongoDB support transactions? 75 | 76 | MongoDB does not support multi-document transactions. However, MongoDB does provide atomic operations on a single document. 77 | 78 | For more details on MongoDB’s isolation guarantees and behavior under concurrency, see[FAQ: Concurrency](https://docs.mongodb.com/manual/faq/concurrency/). 79 | 80 | ## Does MongoDB handle caching? 81 | 82 | Yes. MongoDB keeps most recently used data in RAM. If you have created indexes for your queries and your working data set fits in RAM, MongoDB serves all queries from memory. 83 | 84 | MongoDB does not cache the query results in order to return the cached results for identical queries. 85 | 86 | For more information on MongoDB and memory use, see[WiredTiger and Memory Use](https://docs.mongodb.com/manual/core/wiredtiger/#wiredtiger-ram)and[MMAPv1 and Memory Use](https://docs.mongodb.com/manual/core/mmapv1/#mmapv1-ram). 87 | 88 | ## How does MongoDB address SQL or Query injection? 89 | 90 | ### BSON 91 | 92 | As a client program assembles a query in MongoDB, it builds a BSON object, not a string. Thus traditional SQL injection attacks are not a problem. More details and some nuances are covered below. 93 | 94 | MongoDB represents queries as[BSON](https://docs.mongodb.com/manual/reference/glossary/#term-bson)objects. Typically[client libraries](https://docs.mongodb.com/manual/applications/drivers/)provide a convenient, injection free, process to build these objects. Consider the following C++ example: 95 | 96 | ``` 97 | BSONObj my_query = BSON( "name" << a_name ); 98 | auto_ptr cursor = c.query("tutorial.persons", my_query); 99 | ``` 100 | 101 | Here,`my_query`then will have a value such as`{name:"Joe"}`. If`my_query`contained special characters, for example`,`,`:`, and`{`, the query simply wouldn’t match any documents. For example, users cannot hijack a query and convert it to a delete. 102 | 103 | ### JavaScript 104 | 105 | NOTE 106 | 107 | You can disable all server-side execution of JavaScript, by passing the`--noscripting`option on the command line or setting[`security.javascriptEnabled`](https://docs.mongodb.com/manual/reference/configuration-options/#security.javascriptEnabled)in a configuration file. 108 | 109 | All of the following MongoDB operations permit you to run arbitrary JavaScript expressions directly on the server: 110 | 111 | * [`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where) 112 | * [`mapReduce`](https://docs.mongodb.com/manual/reference/command/mapReduce/#dbcmd.mapReduce) 113 | * [`group`](https://docs.mongodb.com/manual/reference/command/group/#dbcmd.group) 114 | 115 | You must exercise care in these cases to prevent users from submitting malicious JavaScript. 116 | 117 | Fortunately, you can express most queries in MongoDB without JavaScript and for queries that require JavaScript, you can mix JavaScript and non-JavaScript in a single query. Place all the user-supplied fields directly in a[BSON](https://docs.mongodb.com/manual/reference/glossary/#term-bson)field and pass JavaScript code to the[`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where)field. 118 | 119 | If you need to pass user-supplied values in a[`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where)clause, you may escape these values with the`CodeWScope`mechanism. When you set user-submitted values as variables in the scope document, you can avoid evaluating them on the database server. 120 | 121 | -------------------------------------------------------------------------------- /geo-queries/example.md: -------------------------------------------------------------------------------- 1 | # Find Restaurants with Geospatial Queries 2 | 3 | On this page 4 | 5 | * [Overview](https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/#overview) 6 | * [Distortion](https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/#distortion) 7 | * [Searching for Restaurants](https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/#searching-for-restaurants) 8 | 9 | ## Overview 10 | 11 | MongoDB’s[geospatial](https://docs.mongodb.com/manual/reference/glossary/#term-geospatial)indexing allows you to efficiently execute spatial queries on a collection that contains geospatial shapes and points. This tutorial will briefly introduce the concepts of geospatial indexes, and then demonstrate their use with[`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin),[`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects), and[`geoNear`](https://docs.mongodb.com/manual/reference/command/geoNear/#dbcmd.geoNear). 12 | 13 | To showcase the capabilities of geospatial features and compare different approaches, this tutorial will guide you through the process of writing queries for a simple geospatial application. 14 | 15 | Suppose you are designing a mobile application to help users find restaurants in New York City. The application must: 16 | 17 | * Determine the user’s current neighborhood using 18 | [`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects) 19 | , 20 | * Show the number of restaurants in that neighborhood using 21 | [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin) 22 | , and 23 | * Find restaurants within a specified distance of the user using 24 | [`$nearSphere`](https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere) 25 | . 26 | 27 | This tutorial will use a`2dsphere`index to query for this data on spherical geometry. 28 | 29 | For more information on spherical and flat geometries, see[Geospatial Models](https://docs.mongodb.com/manual/geospatial-queries/#geospatial-geometry). 30 | 31 | ## Distortion 32 | 33 | Spherical geometry will appear distorted when visualized on a map due to the nature of projecting a three dimensional sphere, such as the earth, onto a flat plane. 34 | 35 | For example, take the specification of the spherical square defined by the longitude latitude points`(0,0)`,`(80,0)`,`(80,80)`, and`(0,80)`. The following figure depicts the area covered by this region: 36 | 37 | ![](https://docs.mongodb.com/manual/_images/geospatial-spherical-square.png "Diagram of a square projected onto a sphere.") 38 | 39 | ## Searching for Restaurants 40 | 41 | ### Prerequisites 42 | 43 | Download the example datasets from[https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/neighborhoods.json](https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/neighborhoods.json)and[https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json](https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json). These contain the collections`restaurants`and`neighborhoods`respectively. 44 | 45 | After downloading the datasets, import them into the database: 46 | 47 | ``` 48 | mongoimport 49 | < 50 | path 51 | to 52 | restaurants 53 | . 54 | json 55 | > 56 | - 57 | c 58 | restaurants 59 | mongoimport 60 | < 61 | path 62 | to 63 | neighborhoods 64 | . 65 | json 66 | > 67 | - 68 | c 69 | neighborhoods 70 | ``` 71 | 72 | The[`geoNear`](https://docs.mongodb.com/manual/reference/command/geoNear/#dbcmd.geoNear)command requires a geospatial index, and almost always improves performance of[`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin)and[`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects)queries. 73 | 74 | Because this data is geographical, create a`2dsphere`index on each collection using the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 75 | 76 | ``` 77 | db 78 | . 79 | restaurants 80 | . 81 | createIndex 82 | ({ 83 | location 84 | : 85 | "2dsphere" 86 | }) 87 | db 88 | . 89 | neighborhoods 90 | . 91 | createIndex 92 | ({ 93 | geometry 94 | : 95 | "2dsphere" 96 | }) 97 | ``` 98 | 99 | ### Exploring the Data 100 | 101 | Inspect an entry in the newly-created`restaurants`collection from within the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 102 | 103 | ``` 104 | db 105 | . 106 | restaurants 107 | . 108 | findOne 109 | () 110 | ``` 111 | 112 | This query returns a document like the following: 113 | 114 | ``` 115 | { 116 | location 117 | : 118 | { 119 | type 120 | : 121 | "Point" 122 | , 123 | coordinates 124 | : 125 | [ 126 | - 127 | 73.856077 128 | , 129 | 40.848447 130 | ] 131 | }, 132 | name 133 | : 134 | "Morris Park Bake Shop" 135 | } 136 | ``` 137 | 138 | This restaurant document corresponds to the location shown in the following figure: 139 | 140 | ![](https://docs.mongodb.com/manual/_images/geospatial-single-point.png "Map of a single geospatial point.") 141 | 142 | Because the tutorial uses a`2dsphere`index, the geometry data in the`location`field must follow the[GeoJSON format](https://docs.mongodb.com/manual/reference/geojson/). 143 | 144 | Now inspect an entry in the`neighborhoods`collection: 145 | 146 | ``` 147 | db 148 | . 149 | neighborhoods 150 | . 151 | findOne 152 | () 153 | ``` 154 | 155 | This query will return a document like the following: 156 | 157 | ``` 158 | { 159 | geometry 160 | : 161 | { 162 | type 163 | : 164 | "Polygon" 165 | , 166 | coordinates 167 | : 168 | [[ 169 | [ 170 | - 171 | 73.99 172 | , 173 | 40.75 174 | ], 175 | ... 176 | [ 177 | - 178 | 73.98 179 | , 180 | 40.76 181 | ], 182 | [ 183 | - 184 | 73.99 185 | , 186 | 40.75 187 | ] 188 | ]] 189 | }, 190 | name 191 | : 192 | "Hell's Kitchen" 193 | } 194 | ``` 195 | 196 | This geometry corresponds to the region depicted in the following figure: 197 | 198 | ![](https://docs.mongodb.com/manual/_images/geospatial-polygon-hells-kitchen.png "Map of a geospatial polygon.") 199 | 200 | ### Find the Current Neighborhood 201 | 202 | Assuming the user’s mobile device can give a reasonably accurate location for the user, it is simple to find the user’s current neighborhood with[`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects). 203 | 204 | Suppose the user is located at -73.93414657 longitude and 40.82302903 latitude. To find the current neighborhood, you will specify a point using the special[`$geometry`](https://docs.mongodb.com/manual/reference/operator/query/geometry/#op._S_geometry)field in[GeoJSON](https://docs.mongodb.com/manual/reference/glossary/#term-geojson)format: 205 | 206 | ``` 207 | db 208 | . 209 | neighborhoods 210 | . 211 | findOne 212 | ({ 213 | geometry 214 | : 215 | { 216 | $geoIntersects 217 | : 218 | { 219 | $geometry 220 | : 221 | { 222 | type 223 | : 224 | "Point" 225 | , 226 | coordinates 227 | : 228 | [ 229 | - 230 | 73.93414657 231 | , 232 | 40.82302903 233 | ] 234 | } 235 | } 236 | } 237 | }) 238 | ``` 239 | 240 | This query will return the following result: 241 | 242 | ``` 243 | { 244 | "_id" 245 | : 246 | ObjectId 247 | ( 248 | "55cb9c666c522cafdb053a68" 249 | ), 250 | "geometry" 251 | : 252 | { 253 | "type" 254 | : 255 | "Polygon" 256 | , 257 | "coordinates" 258 | : 259 | [ 260 | [ 261 | [ 262 | - 263 | 73.93383000695911 264 | , 265 | 40.81949109558767 266 | ], 267 | ... 268 | ] 269 | ] 270 | }, 271 | "name" 272 | : 273 | "Central Harlem North-Polo Grounds" 274 | } 275 | ``` 276 | 277 | ### Find all Restaurants in the Neighborhood 278 | 279 | You can also query to find all restaurants contained in a given neighborhood. Run the following in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell to find the neighborhood containing the user, and then count the restaurants within that neighborhood: 280 | 281 | ``` 282 | var 283 | neighborhood 284 | = 285 | db 286 | . 287 | neighborhoods 288 | . 289 | findOne 290 | ( 291 | { 292 | geometry 293 | : 294 | { 295 | $geoIntersects 296 | : 297 | { 298 | $geometry 299 | : 300 | { 301 | type 302 | : 303 | "Point" 304 | , 305 | coordinates 306 | : 307 | [ 308 | - 309 | 73.93414657 310 | , 311 | 40.82302903 312 | ] 313 | } 314 | } 315 | } 316 | } 317 | ) 318 | db 319 | . 320 | restaurants 321 | . 322 | find 323 | ( 324 | { 325 | location 326 | : 327 | { 328 | $geoWithin 329 | : 330 | { 331 | $geometry 332 | : 333 | neighborhood 334 | . 335 | geometry 336 | } 337 | } 338 | } 339 | ). 340 | count 341 | () 342 | ``` 343 | 344 | This query will tell you that there are 127 restaurants in the requested neighborhood, visualized in the following figure: 345 | 346 | ![](https://docs.mongodb.com/manual/_images/geospatial-all-restaurants.png "Map of all restaurants in a geospatial polygon.") 347 | 348 | ### Find Restaurants within a Distance 349 | 350 | To find restaurants within a specified distance of a point, you can use either[`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin)with[`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)to return results in unsorted order, or`nearSphere`with[`$maxDistance`](https://docs.mongodb.com/manual/reference/operator/query/maxDistance/#op._S_maxDistance)if you need results sorted by distance. 351 | 352 | ### Unsorted with`$geoWithin` 353 | 354 | To find restaurants within a circular region, use[`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin)with[`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere).[`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)is a MongoDB-specific syntax to denote a circular region by specifying the center and the radius in radians. 355 | 356 | [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin)does not return the documents in any specific order, so it may show the user the furthest documents first. 357 | 358 | The following will find all restaurants within five miles of the user: 359 | 360 | ``` 361 | db 362 | . 363 | restaurants 364 | . 365 | find 366 | ({ 367 | location 368 | : 369 | { 370 | $geoWithin 371 | : 372 | { 373 | $centerSphere 374 | : 375 | [ 376 | [ 377 | - 378 | 73.93414657 379 | , 380 | 40.82302903 381 | ], 382 | 5 383 | / 384 | 3963.2 385 | ] 386 | } 387 | } 388 | }) 389 | ``` 390 | 391 | [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)’s second argument accepts the radius in radians, so you must divide it by the radius of the earth in miles. See[Calculate Distance Using Spherical Geometry](https://docs.mongodb.com/manual/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes/)for more information on converting between distance units. 392 | 393 | ### Sorted with`$nearSphere` 394 | 395 | You may also use[`$nearSphere`](https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere)and specify a[`$maxDistance`](https://docs.mongodb.com/manual/reference/operator/query/maxDistance/#op._S_maxDistance)term in meters. This will return all restaurants within five miles of the user in sorted order from nearest to farthest: 396 | 397 | ``` 398 | var 399 | METERS_PER_MILE 400 | = 401 | 1609.34 402 | db 403 | . 404 | restaurants 405 | . 406 | find 407 | ({ 408 | location 409 | : 410 | { 411 | $nearSphere 412 | : 413 | { 414 | $geometry 415 | : 416 | { 417 | type 418 | : 419 | "Point" 420 | , 421 | coordinates 422 | : 423 | [ 424 | - 425 | 73.93414657 426 | , 427 | 40.82302903 428 | ] 429 | }, 430 | $maxDistance 431 | : 432 | 5 433 | * 434 | METERS_PER_MILE 435 | } 436 | } 437 | }) 438 | ``` 439 | 440 | 441 | 442 | -------------------------------------------------------------------------------- /indexes/single-field.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElemeFE/mongodb-doc-cn/c7c6e7167f498ad0a99da50af32897baa84b7f2b/indexes/single-field.md -------------------------------------------------------------------------------- /introduction/README.md: -------------------------------------------------------------------------------- 1 | # MongoDB 简介 2 | 3 | 本页索引: 4 | 5 | * [文档数据库](#文档数据库) 6 | * [关键特性](#关键特性) 7 | 8 | MongoDB 是一个提供了高性能、高可用以及自动伸缩(auto scaling)功能的开源的文档数据库 (Document Database). 9 | 10 | ## 文档数据库 11 | 12 | 在 MongoDB 中一条记录 (record) 就是一个文档 (document), 文档本身类似 JSON 对象, 其数据结构是组合的键值对. 值可以是其他文档, 数组或者一个文档的数组等. 13 | 14 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-document.bakedsvg.svg "A MongoDB document.") 15 | 16 | 文档的优势在于: 17 | 18 | * 文档 \(如 Object\) 可以对应到许多编程语言内置的数据类型. 19 | * 内嵌的文档和数组结构减少了昂贵的跨表 (join) 查询. 20 | * 自由的表结构 (Dynamic schema) 支持流畅的多态. 21 | 22 | ## 关键特性 23 | 24 | ### 高性能 25 | 26 | MongoDB 提供了高性能的数据持久化. 特别是, 27 | 28 | * 通过嵌入式的数据模型来减少 I/O 操作. 29 | * 索引可以支持快速的查询, 还可以通过通过深层结构的 (embedded) 文档和数组作为 key. 30 | 31 | ### 丰富的查询语句 32 | 33 | MongoDB 拥有丰富的查询语句来进行 [读写操作 \(CRUD\)](https://docs.mongodb.com/manual/crud/) 以及: 34 | 35 | * [数据聚合 (Aggregation)](https://docs.mongodb.com/manual/core/aggregation-pipeline/) 36 | * [文本搜索](https://docs.mongodb.com/manual/text-search/) 37 | 和 38 | [地理位置查询](https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/) 39 | . 40 | 41 | ### 高可用 42 | 43 | MongoDB 的备份功能, 名为[复制集 (replica set)](https://docs.mongodb.com/manual/replication/), 提供: 44 | 45 | * _自动_ 熔断 (failover) 46 | * 数据冗余 47 | 48 | 一个[复制集](https://docs.mongodb.com/manual/replication/)是一组维护相同数据集的 MongoDB 实例, 提供了冗余和新增数据的可用性. 49 | 50 | ### 水平拓展 51 | 52 | MongoDB 将水平拓展性作为它的 _核心_ 功能: 53 | 54 | * [分片 (Sharding)](https://docs.mongodb.com/manual/sharding/#sharding-introduction) 55 | 将数据分布在一个集群的机器上. 56 | * MongoDB 3.4 支持根据 [shard key](https://docs.mongodb.com/manual/reference/glossary/#term-shard-key) 创建 57 | 数据[区域 (zones)](https://docs.mongodb.com/manual/core/zone-sharding/#zone-sharding). 在一个均衡的集群中, MongoDB 根据分区直接读写区域中的节点. 阅读 58 | [区域](https://docs.mongodb.com/manual/core/zone-sharding/#zone-sharding) 59 | 手册了解更多. 60 | 61 | ### 支持多种存储引擎 62 | 63 | MongoDB 支持[多个存储引擎](https://docs.mongodb.com/manual/core/storage-engines/), 如: 64 | 65 | * [WiredTiger 存储引擎](https://docs.mongodb.com/manual/core/wiredtiger/) 66 | and 67 | * [MMAPv1 存储引擎](https://docs.mongodb.com/manual/core/mmapv1/) 68 | . 69 | 70 | 此外, MongoDB 还提供了允许第三方的人员为 MongoDB 开发的插件 API. 71 | 72 | -------------------------------------------------------------------------------- /introduction/bson.md: -------------------------------------------------------------------------------- 1 | # BSON Types 2 | 3 | On this page 4 | 5 | * [ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid) 6 | * [String](https://docs.mongodb.com/manual/reference/bson-types/#string) 7 | * [Timestamps](https://docs.mongodb.com/manual/reference/bson-types/#timestamps) 8 | * [Date](https://docs.mongodb.com/manual/reference/bson-types/#date) 9 | 10 | [BSON](https://docs.mongodb.com/manual/reference/glossary/#term-bson)is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at[bsonspec.org](http://bsonspec.org/). 11 | 12 | Each BSON type has both integer and string identifiers as listed in the following table: 13 | 14 | | Type | Number | Alias | Notes | 15 | | :--- | :--- | :--- | :--- | 16 | | Double | 1 | “double” | | 17 | | String | 2 | “string” | | 18 | | Object | 3 | “object” | | 19 | | Array | 4 | “array” | | 20 | | Binary data | 5 | “binData” | | 21 | | Undefined | 6 | “undefined” | Deprecated. | 22 | | ObjectId | 7 | “objectId” | | 23 | | Boolean | 8 | “bool” | | 24 | | Date | 9 | “date” | | 25 | | Null | 10 | “null” | | 26 | | Regular Expression | 11 | “regex” | | 27 | | DBPointer | 12 | “dbPointer” | Deprecated. | 28 | | JavaScript | 13 | “javascript” | | 29 | | Symbol | 14 | “symbol” | Deprecated. | 30 | | JavaScript \(with scope\) | 15 | “javascriptWithScope” | | 31 | | 32-bit integer | 16 | “int” | | 32 | | Timestamp | 17 | “timestamp” | | 33 | | 64-bit integer | 18 | “long” | | 34 | | Decimal128 | 19 | “decimal” | New in version 3.4. | 35 | | Min key | -1 | “minKey” | | 36 | | Max key | 127 | “maxKey” | | 37 | 38 | You can use these values with the[`$type`](https://docs.mongodb.com/manual/reference/operator/query/type/#op._S_type)operator to query documents by their BSON type. The[`$type`](https://docs.mongodb.com/manual/reference/operator/aggregation/type/#exp._S_type)aggregation operator returns the type of an[operator expression](https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#agg-quick-ref-operator-expressions)using one of the listed BSON type strings. 39 | 40 | To determine a field’s type, see[Check Types in the mongo Shell](https://docs.mongodb.com/manual/core/shell-types/#check-types-in-shell). 41 | 42 | If you convert BSON to JSON, see the[Extended JSON](https://docs.mongodb.com/manual/reference/mongodb-extended-json/)reference. 43 | 44 | The following sections describe special considerations for particular BSON types. 45 | 46 | ## ObjectId 47 | 48 | ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation. Specifically: 49 | 50 | * a 4-byte value representing the seconds since the Unix epoch, 51 | * a 3-byte machine identifier, 52 | * a 2-byte process id, and 53 | * a 3-byte counter, starting with a random value. 54 | 55 | In MongoDB, each document stored in a collection requires a unique[\_id](https://docs.mongodb.com/manual/reference/glossary/#term-id)field that acts as a[primary key](https://docs.mongodb.com/manual/reference/glossary/#term-primary-key). If an inserted document omits the`_id`field, the MongoDB driver automatically generates an[ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid)for the`_id`field. 56 | 57 | This also applies to documents inserted through update operations with[upsert: true](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-parameter). 58 | 59 | MongoDB clients should add an`_id`field with a unique ObjectId. Using ObjectIds for the`_id`field provides the following additional benefits: 60 | 61 | * in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, you can access the creation time of the`ObjectId`, using the[`ObjectId.getTimestamp()`](https://docs.mongodb.com/manual/reference/method/ObjectId.getTimestamp/#ObjectId.getTimestamp)method. 62 | 63 | * sorting on an`_id`field that stores`ObjectId`values is roughly equivalent to sorting by creation time. 64 | 65 | IMPORTANT 66 | 67 | The relationship between the order of`ObjectId`values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second;`ObjectId`values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values because client drivers generate`ObjectId`values. 68 | 69 | SEE ALSO 70 | 71 | [`ObjectId()`](https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectId) 72 | 73 | ## String 74 | 75 | BSON strings are UTF-8. In general, drivers for each programming language convert from the language’s string format to UTF-8 when serializing and deserializing BSON. This makes it possible to store most international characters in BSON strings with ease.[\[1\]](https://docs.mongodb.com/manual/reference/bson-types/#sort-string-internationalization)In addition, MongoDB[`$regex`](https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex)queries support UTF-8 in the regex string. 76 | 77 | | [\[1\]](https://docs.mongodb.com/manual/reference/bson-types/#id3) | Given strings using UTF-8 character sets, using[`sort()`](https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort)on strings will be reasonably correct. However, because internally[`sort()`](https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort)uses the C++`strcmp`api, the sort order may handle some characters incorrectly. | 78 | | :--- | :--- | 79 | 80 | 81 | ## Timestamps 82 | 83 | BSON has a special timestamp type for_internal_MongoDB use and is**not**associated with the regular[Date](https://docs.mongodb.com/manual/reference/bson-types/#document-bson-type-date)type. Timestamp values are a 64 bit value where: 84 | 85 | * the first 32 bits are a 86 | `time_t` 87 | value \(seconds since the Unix epoch\) 88 | * the second 32 bits are an incrementing 89 | `ordinal` 90 | for operations within a given second. 91 | 92 | Within a single[`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)instance, timestamp values are always unique. 93 | 94 | In replication, the[oplog](https://docs.mongodb.com/manual/reference/glossary/#term-oplog)has a`ts`field. The values in this field reflect the operation time, which uses a BSON timestamp value. 95 | 96 | NOTE 97 | 98 | The BSON timestamp type is for_internal_MongoDB use. For most cases, in application development, you will want to use the BSON date type. See[Date](https://docs.mongodb.com/manual/reference/bson-types/#document-bson-type-date)for more information. 99 | 100 | If you insert a document containing an empty BSON timestamp in a top-level field, the MongoDB server will replace that empty timestamp with the current timestamp value. For example, if you create an insert a document with a timestamp value, as in the following operation: 101 | 102 | ``` 103 | var 104 | a 105 | = 106 | new 107 | Timestamp 108 | (); 109 | db 110 | . 111 | test 112 | . 113 | insertOne 114 | ( 115 | { 116 | ts 117 | : 118 | a 119 | } 120 | ); 121 | ``` 122 | 123 | Then, the[`db.test.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)operation will return a document that resembles the following: 124 | 125 | ``` 126 | { 127 | "_id" 128 | : 129 | ObjectId 130 | ( 131 | "542c2b97bac0595474108b48" 132 | ), 133 | "ts" 134 | : 135 | Timestamp 136 | ( 137 | 1412180887 138 | , 139 | 1 140 | ) 141 | } 142 | ``` 143 | 144 | If`ts`were a field in an embedded document, the server would have left it as an empty timestamp value. 145 | 146 | Changed in version 2.6:Previously, the server would only replace empty timestamp values in the first two fields, including`_id`, of an inserted document. Now MongoDB will replace any top-level field. 147 | 148 | ## Date 149 | 150 | BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch \(Jan 1, 1970\). This results in a representable date range of about 290 million years into the past and future. 151 | 152 | The[official BSON specification](http://bsonspec.org/#/specification)refers to the BSON Date type as the_UTC datetime_. 153 | 154 | BSON Date type is signed.[\[2\]](https://docs.mongodb.com/manual/reference/bson-types/#unsigned-date)Negative values represent dates before 1970. 155 | 156 | EXAMPLE 157 | 158 | Construct a Date using the`newDate()`constructor in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 159 | 160 | ``` 161 | var 162 | mydate1 163 | = 164 | new 165 | Date 166 | () 167 | ``` 168 | 169 | EXAMPLE 170 | 171 | Construct a Date using the`ISODate()`constructor in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 172 | 173 | ``` 174 | var 175 | mydate2 176 | = 177 | ISODate 178 | () 179 | ``` 180 | 181 | EXAMPLE 182 | 183 | Return the`Date`value as string: 184 | 185 | ``` 186 | mydate1 187 | . 188 | toString 189 | () 190 | ``` 191 | 192 | EXAMPLE 193 | 194 | Return the month portion of the Date value; months are zero-indexed, so that January is month`0`: 195 | 196 | ``` 197 | mydate1 198 | . 199 | getMonth 200 | () 201 | ``` 202 | 203 | | [\[2\]](https://docs.mongodb.com/manual/reference/bson-types/#id4) | Prior to version 2.0,`Date`values were incorrectly interpreted as_unsigned_integers, which affected sorts, range queries, and indexes on`Date`fields. Because indexes are not recreated when upgrading, please re-index if you created an index on`Date`values with an earlier version, and dates before 1970 are relevant to your application. | 204 | | :--- | :--- | 205 | 206 | 207 | 208 | 209 | -------------------------------------------------------------------------------- /introduction/capped-col.md: -------------------------------------------------------------------------------- 1 | # 封顶集合 2 | 3 | 本文索引 4 | 5 | * [概述](#概述) 6 | * [表现](#表现) 7 | * [限制与推荐](#限制与推荐) 8 | * [使用](#使用) 9 | 10 | ## 概述 11 | 12 | 封顶集合 [capped collection](https://docs.mongodb.com/manual/reference/glossary/#term-capped-collection) 是固定大小的集合, 支持高吞吐的插入操作和根据插入顺序的查询操作. 封顶集合的工作方式与循环缓冲区 (circular buffers) 类似: 当一个集合填满了被分配的空间, 则通过覆盖最早的文档来为新的文档腾出空间. 13 | 14 | 参阅 [`createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection) 或 [`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create) 获取更多创建封顶集合的信息. 15 | 16 | ## 表现 17 | 18 | ### 顺序插入 19 | 20 | 封顶集合保证了插入的顺序. 因此, 历史查询不需要索引排序. 没有这种索引开销, 封顶集合可以支持更高的插入吞吐量. 21 | 22 | ### 自动删除最早的文档 23 | 24 | 为了给新的文档腾出空间, 封顶集合会自动删除集合中最早的文档, 不需要定时脚本或者显示的删除操作. 25 | 26 | 例如, 在 [oplog.rs](https://docs.mongodb.com/manual/reference/glossary/#term-oplog) 集合中存储了 [replica set](https://docs.mongodb.com/manual/reference/glossary/#term-replica-set) 的操作的日志, 该集合就使用的是封顶集合. 除此之外, 还可以考虑以下潜在的用例: 27 | 28 | * 存储由高容量 (high-volume) 系统生成的日志信息. 在封顶集合中不用索引插入文档的速度接近直接输出日志到文件系统. 而且, 内置的 _先进先出_ 的属性维护了事件的顺序, 这在管理存储时用得到 (译注: 有些日志存储系统的顺序可能会乱, 如 Elasticsearch). 29 | * 在封顶集合中记性数据缓存 (少量的). 由于缓存是高频读很少写, 因此你需要确保集合 _始终_ 保留在工作区间 \(即 RAM 中\) _或者_ 接受一些使用索引带来的写入的成本 (or accept some write penalty for the required index or indexes 30 | ). 31 | 32 | ### `_id` 索引 33 | 34 | 封顶集合有 `_id` 字段并且有一个基于 `_id` 字段的默认索引. 35 | 36 | ## 限制与推荐 37 | 38 | ### 更新 39 | 40 | 如果您计划更新封顶集合中的文档, 请创建一个索引, 来避免更新操进行集合扫描. 41 | 42 | ### 文档大小 43 | 44 | 在 3.2 版本中修改. 45 | 46 | 更新或替换文档大小的操作会失败. (注: 之前的 MMAPv1 可以修改) 47 | 48 | ### 文档删除 49 | 50 | 你不能删除封顶集合中的文档. 要删除集合中的所有文档, 请使用 [`drop()`](https://docs.mongodb.com/manual/reference/method/db.collection.drop/#db.collection.drop) 方法删除集合, 并重新创建封顶的集合. 51 | 52 | ### 分片 53 | 54 | 你不能对封顶集合进行分片操作. 55 | 56 | ### 查询效率 57 | 58 | 使用自然顺序 (natural ordering) 来有效地检索集合最近插入的元素. 这 \(有点\) 类似 `tail` 一个日志文件 (查看他的尾部). 59 | 60 | ### 聚合 `$out` 61 | 62 | 聚合管道操作符 [`$out`](https://docs.mongodb.com/manual/reference/operator/aggregation/out/#pipe._S_out)不能将结果写入封顶集合. 63 | 64 | ## 使用 65 | 66 | ### 创建封顶集合 67 | 68 | When creating a capped collection you must specify the maximum size of the collection in bytes, which MongoDB will pre-allocate for the collection. The size of the capped collection includes a small amount of space for internal overhead. 69 | 70 | 您必须使用 [`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection) 方法显式地创建封顶集合, 该过程可以通过 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) shell 来帮忙执行 [`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create) 命令. 在创建封顶集合时, 您必须预先指定集合的最大容量 (以字节为单位). 其中包括少量的内部空间. 71 | 72 | ``` 73 | db.createCollection( "log", { capped: true, size: 100000 } ) 74 | ``` 75 | 76 | 如果 `size` 字段小于或等于 4096, 则该集合将具有 4096 字节的容量. 此外, MongoDB 会提升用户所提供给的 size 大小直到其满足 256 的倍数为止. 77 | 78 | Additionally, you may also specify a maximum number of documents for the collection using the`max`field as in the following document: 79 | 80 | ``` 81 | db.createCollection("log", { capped : true, size : 5242880, max : 5000 } ) 82 | ``` 83 | 84 | > IMPORTANT 85 | > 86 | > The`size`argument is_always_required, even when you specify`max`number of documents. MongoDB will remove older documents if a collection reaches the maximum size limit before it reaches the maximum document count. 87 | > 88 | 89 | SEE 90 | 91 | [`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)and[`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create). 92 | 93 | ### 封顶集合查询 94 | 95 | If you perform a[`find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)on a capped collection with no ordering specified, MongoDB guarantees that the ordering of results is the same as the insertion order. 96 | 97 | To retrieve documents in reverse insertion order, issue[`find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)along with the[`sort()`](https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort)method with the[`$natural`](https://docs.mongodb.com/manual/reference/operator/meta/natural/#metaOp._S_natural)parameter set to`-1`, as shown in the following example: 98 | 99 | ``` 100 | db.cappedCollection.find().sort( { $natural: -1 } ) 101 | ``` 102 | 103 | ### 检查集合是否封顶 104 | 105 | Use the[`isCapped()`](https://docs.mongodb.com/manual/reference/method/db.collection.isCapped/#db.collection.isCapped)method to determine if a collection is capped, as follows: 106 | 107 | ``` 108 | db.collection.isCapped() 109 | ``` 110 | 111 | ### 集合转换为封顶集合 112 | 113 | You can convert a non-capped collection to a capped collection with the[`convertToCapped`](https://docs.mongodb.com/manual/reference/command/convertToCapped/#dbcmd.convertToCapped)command: 114 | 115 | ``` 116 | db.runCommand({"convertToCapped": "mycoll", size: 100000}); 117 | ``` 118 | 119 | The`size`parameter specifies the size of the capped collection in bytes. 120 | 121 | > WARNING 122 | > 123 | > This command obtains a global write lock and will block other operations until it has completed. 124 | > 125 | 126 | ### Automatically Remove Data After a Specified Period of Time 127 | 128 | As an alternative to 封顶集合, consider MongoDB’s[TTL](https://docs.mongodb.com/manual/reference/glossary/#term-ttl)\(“_time to live_”\) indexes. As described in[Expire Data from Collections by Setting TTL](https://docs.mongodb.com/manual/tutorial/expire-data/), these indexes allow you to expire and remove data from normal collections based on the value of a date-typed field and a TTL value for the index. 129 | 130 | > IMPORTANT 131 | > 132 | > [TTL indexes](https://docs.mongodb.com/manual/tutorial/expire-data/)are not compatible with 封顶集合. 133 | > 134 | 135 | ### Tailable Cursor 136 | 137 | You can use a[tailable cursor](https://docs.mongodb.com/manual/reference/glossary/#term-tailable-cursor)with 封顶集合. Similar to the Unix`tail-f`command, the tailable cursor “tails” the end of a capped collection. As new documents are inserted into the capped collection, you can use the tailable cursor to continue retrieving documents. 138 | 139 | See[Tailable Cursors](https://docs.mongodb.com/manual/core/tailable-cursors/)for information on creating a tailable cursor. 140 | 141 | -------------------------------------------------------------------------------- /introduction/comparison-sort-order.md: -------------------------------------------------------------------------------- 1 | # Comparison/Sort Order 2 | 3 | On this page 4 | 5 | * [Numeric Types](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#numeric-types) 6 | * [Strings](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#strings) 7 | * [Arrays](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#arrays) 8 | * [Dates and Timestamps](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#dates-and-timestamps) 9 | * [Non-existent Fields](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#non-existent-fields) 10 | * [BinData](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#bindata) 11 | 12 | When comparing values of different[BSON types](https://docs.mongodb.com/manual/reference/bson-types/#bson-types), MongoDB uses the following comparison order, from lowest to highest: 13 | 14 | 1. MinKey \(internal type\) 15 | 2. Null 16 | 3. Numbers \(ints, longs, doubles, decimals\) 17 | 4. Symbol, String 18 | 5. Object 19 | 6. Array 20 | 7. BinData 21 | 8. ObjectId 22 | 9. Boolean 23 | 10. Date 24 | 11. Timestamp 25 | 12. Regular Expression 26 | 13. MaxKey \(internal type\) 27 | 28 | ## Numeric Types 29 | 30 | MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison. 31 | 32 | ## Strings 33 | 34 | ### Binary Comparison 35 | 36 | By default, MongoDB uses the simple binary comparison to compare strings. 37 | 38 | ### Collation 39 | 40 | New in version 3.4. 41 | 42 | [Collation](https://docs.mongodb.com/manual/reference/collation/)allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. 43 | 44 | Collation specification has the following syntax: 45 | 46 | ``` 47 | { 48 | locale 49 | : 50 | < 51 | string 52 | > 53 | , 54 | caseLevel 55 | : 56 | < 57 | boolean 58 | > 59 | , 60 | caseFirst 61 | : 62 | < 63 | string 64 | > 65 | , 66 | strength 67 | : 68 | < 69 | int 70 | > 71 | , 72 | numericOrdering 73 | : 74 | < 75 | boolean 76 | > 77 | , 78 | alternate 79 | : 80 | < 81 | string 82 | > 83 | , 84 | maxVariable 85 | : 86 | < 87 | string 88 | > 89 | , 90 | backwards 91 | : 92 | < 93 | boolean 94 | > 95 | } 96 | ``` 97 | 98 | When specifying collation, the`locale`field is mandatory; all other collation fields are optional. For descriptions of the fields, see[Collation Document](https://docs.mongodb.com/manual/reference/collation/#collation-document-fields). 99 | 100 | If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons. 101 | 102 | ## Arrays 103 | 104 | With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays. As such, when comparing a field whose value is a single-element array \(e.g.`[1]`\) with non-array fields \(e.g.`2`\), the comparison is between`1`and`2`. A comparison of an empty array \(e.g.`[]`\) treats the empty array as less than`null`or a missing field. 105 | 106 | ## Dates and Timestamps 107 | 108 | Changed in version 3.0.0:Date objects sort before Timestamp objects. Previously Date and Timestamp objects sorted together. 109 | 110 | ## Non-existent Fields 111 | 112 | The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on the`a`field in documents`{}`and`{a:null}`would treat the documents as equivalent in sort order. 113 | 114 | ## BinData 115 | 116 | MongoDB sorts`BinData`in the following order: 117 | 118 | 1. First, the length or size of the data. 119 | 2. Then, by the BSON one-byte subtype. 120 | 3. Finally, by the data, performing a byte-by-byte comparison. 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /introduction/db-and-collections.md: -------------------------------------------------------------------------------- 1 | # 数据库 & 集合 2 | 3 | 本页索引 4 | 5 | * [数据库](#数据库) 6 | * [集合](#集合) 7 | 8 | MongoDB 在 [集合](https://docs.mongodb.com/manual/reference/glossary/#term-collection) 中存储 [BSON 文档](https://docs.mongodb.com/manual/core/document/#bson-document-format)作为数据记录. 数据库中的集合: 9 | 10 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-collection.bakedsvg.svg "A collection of MongoDB documents.") 11 | 12 | ## 数据库 13 | 14 | 在 MongoDB 中一个数据库对应多个集合, 一个集合对应多个文档. 15 | 16 | 要找一个数据库来用, 可以在 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) shell 中使用 `use ` 语句, 如下例所示: 17 | 18 | ```bash 19 | use myDB 20 | ``` 21 | 22 | ### 创建数据库 23 | 24 | 如果数据库不存在, MongoDB 在你第一次存储数据的时候默认帮你创建数据库. 例如, 你可以切换到一个不存在的数据库然后执行下例操作: 25 | 26 | ```js 27 | use myNewDB 28 | 29 | db.myNewCollection1.insertOne( { x: 1 } ) 30 | ``` 31 | 32 | 其中 [`insertOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne) 操作同时创建了名为 `myNewDB` 的数据库以及名为 `myNewCollection1` 的集合 (如果它们之前没有的话). 33 | 34 | 关于数据库名称的限制, 参阅 [Naming Restrictions](https://docs.mongodb.com/manual/reference/limits/#restrictions-on-db-names). 35 | 36 | ## 集合 37 | 38 | MongoDB 将文档存储在集合中. 集合类似关系型数据库中表的概念. 39 | 40 | ### 创建集合 41 | 42 | 如果集合不存在, MongoDB 会在你第一次存储数据到集合时默认创建. 43 | 44 | ```js 45 | db.myNewCollection2.insertOne( { x: 1 } ) 46 | db.myNewCollection3.createIndex( { y: 1 } ) 47 | ``` 48 | 49 | 不论是 [`insertOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne) 还是 [`createIndex()`](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex) 操作都可以创建它们各自的集合 (如果集合不存在的话). 50 | 51 | 关于集合名称的限制, 参阅 [Naming Restrictions](https://docs.mongodb.com/manual/reference/limits/#restrictions-on-collection-names). 52 | 53 | ### 显示创建 54 | 55 | MongoDB 还提供了 [`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection) 方法来通过选项, 例如设置文档的最大大小或者验证规则, 显示地创建一个集合. 如果你不指定这些选项的花, 你其实不需要显示的创建集合, 毕竟 MongoDB 会在你第一次存储数据到集合时默认创建该集合. 56 | 57 | 如果要修改集合的选项, 参阅 [`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod). 58 | 59 | ### 文档验证 60 | 61 | 3.2 版本中的新功能. 62 | 63 | 默认情况下, 一个集合不需要它的文档都是统一的结构 (schema); 即单个集合中的文档不需要包含同样的字段集以及指定字段的数据类型. 64 | 65 | 从 MongoDB 3.2 开始, 你可以开启[文档验证规则](https://docs.mongodb.com/manual/core/document-validation/) 来确保集合的更新和插入操作. 更多参阅[文档验证](https://docs.mongodb.com/manual/core/document-validation/). 66 | 67 | ### 修改文档结构[¶](#修改文档结构) 68 | 69 | 修改一个集合中文档的结构, 例如添加新的字段, 删除存在的字段, 或者将字段的值修改为新的类型, 更新文档为新的结构等. 70 | 71 | -------------------------------------------------------------------------------- /introduction/document.md: -------------------------------------------------------------------------------- 1 | # Documents 2 | 3 | 本页索引 4 | 5 | * [文档结构](#文档结构) 6 | * [点符号](#点符号) 7 | * [文档限制](#文档限制) 8 | * [文档结构的其他用途](#文档结构的其他用途) 9 | * [其他资源](#其他资源) 10 | 11 | MongoDB 将数据记录存储为 BSON 文档. BSON 是一个 [JSON 的二进制形式](https://docs.mongodb.com/manual/reference/glossary/#term-json) 文档, 虽然它比起 JSON 包含更多的数据类型. 关于 BSON 的规范, 参见 [bsonspec.org](http://bsonspec.org/). 也可以查看本手册的 [BSON 类型](https://docs.mongodb.com/manual/reference/bson-types/). 12 | 13 | ![](https://docs.mongodb.com/manual/_images/crud-annotated-document.bakedsvg.svg "A MongoDB document.") 14 | 15 | ## 文档结构 16 | 17 | MongoDB 文档由 字段-值 成对组成,结构如下: 18 | 19 | ```js 20 | { 21 | field1 : value1, 22 | field2 : value2, 23 | field3 : value3, 24 | ... 25 | fieldN : valueN 26 | } 27 | ``` 28 | 29 | 字段的值可以是任意的 BSON [数据类型](https://docs.mongodb.com/manual/reference/bson-types/), 包括其他的文档, 数组, 或者含文档的数组. 例如, 以下文档包含的不同类型的值: 30 | 31 | ```js 32 | var mydoc = { 33 | _id : ObjectId (“5099803df3f4948bd2f98391” ), 34 | name : { first : “Alan” , last : “Turing” }, 35 | birth : new Date ('Jun 23,1912 ' ), 36 | death : new Date ('Jun 07 ,1954年), 37 | 贡献: [ “图灵机” , “图灵测试” , “Turingery” ] 38 | 观点 : NumberLong (125万) 39 | } 40 | ``` 41 | 42 | 上述字段具有以下数据类型: 43 | 44 | * `_id` 保存了 [ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid). 45 | * `name` 拥有包含 `first`, `last` 字段的 _内嵌文档_. 46 | * `birth` 和 `death` 保存 _Date_ 类型的值. 47 | * `contribs` 拥有 _字符串数组_. 48 | * `views` 保存 _NumberLong_ 类型的值. 49 | 50 | ### 字段名称 51 | 52 | 字段名称是 string 类型. 53 | 54 | [文档](#) 对字段名称有以下一些限制: 55 | 56 | * 字段 `_id` 保留用于主键的; 该字段必须在集合中唯一, 不可改变, 并且可以是数组外的任意类型. 57 | * 字段名称**不能**以 \(`$`\) 符号开头. 58 | * 字段名称**不能**包含 \(`.`\) 字符. 59 | * 字段名称**不能**包含 `null` 字符. 60 | 61 | BSON documents may have more than one field with the same name. Most[MongoDB interfaces](https://docs.mongodb.com/manual/applications/drivers/), however, represent MongoDB with a structure \(e.g. a hash table\) that does not support duplicate 字段名称. If you need to manipulate documents that have more than one field with the same name, see the[driver documentation](https://docs.mongodb.com/manual/applications/drivers/)for your driver. 62 | 63 | Some documents created by internal MongoDB processes may have duplicate fields, but_no_MongoDB process will_ever_add duplicate fields to an existing user document. 64 | 65 | ### 字段值限制 66 | 67 | 对于[有索引的集合](https://docs.mongodb.com/manual/indexes/), 其索引字段有一个 [最大索引 key 长度 (`MaximumIndexKeyLength`)](https://docs.mongodb.com/manual/reference/limits/#Index-Key-Limit) 限制. 详细参见 [`MaximumIndexKeyLength`](https://docs.mongodb.com/manual/reference/limits/#Index-Key-Limit). 68 | 69 | ## 点符号 70 | 71 | MongoDB 使用 _._ 来访问数组中的元素以及内嵌文档中的字段. 72 | 73 | ### 数组 74 | 75 | 要通过基于零的数组位置来指定或访问数组的元素,请使用数组名与 \(`.`\) 和从零开始的数组位置,并用中括号括起来: 76 | 77 | ``` 78 | " < array > . < index > " 79 | ``` 80 | 81 | 例如, 给定如下文档的字段: 82 | 83 | ``` 84 | { 85 | ... 86 | contribs : ["Turing machine", "Turing test", "Turingery"], 87 | ... 88 | } 89 | ``` 90 | 91 | 要指定数组 `contribs` 中的第三个元素, 可以使用 `"contribs.2"`. 92 | 93 | 关于查询数组的, 参见: 94 | 95 | * [Query an Array](https://docs.mongodb.com/manual/tutorial/query-arrays/) 96 | * [Query an Array of Embedded Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) 97 | 98 | 也参见 99 | 100 | * [`$`](https://docs.mongodb.com/manual/reference/operator/update/positional/#up._S_) positional operator for update operations, 101 | * [`$`](https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_) projection operator when array index position is unknown 102 | * [Query an Array](https://docs.mongodb.com/manual/tutorial/query-arrays/#read-operations-arrays) for 点符号 examples with arrays. 103 | 104 | ### 内嵌文档 105 | 106 | 要指定或访问内嵌文档的字段,请将内嵌文档名称与 \(`.`\) 和字段名称连接起来,并用中括号括起来: 107 | 108 | ``` 109 | " < embedded document > . < field > " 110 | ``` 111 | 112 | 例如, 给定如下文档中的字段: 113 | 114 | ``` 115 | { 116 | ... 117 | name : { first : "Alan", last : "Turing"}, 118 | contact : { phone : {type : "cell", number : "111-222-3333"} }, 119 | ... 120 | } 121 | ``` 122 | 123 | * 要指定 `name` 字段中的 `last` 字段, 可以使用 `"name.last"`. 124 | * 要指定 `contact` 下 `phone` 中的 `number` 字段, 可以使用 `"contact.phone.number"`. 125 | 126 | 关于查询内嵌文档, 参见: 127 | 128 | * [Query on Embedded/Nested Documents](https://docs.mongodb.com/manual/tutorial/query-embedded-documents/) 129 | * [Query an Array of Embedded Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) 130 | 131 | ## 文档限制 132 | 133 | ### 文档大小限制 134 | 135 | BSON 文档的最大 size 为 16 MB. 136 | 137 | The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API. See[`mongofiles`](https://docs.mongodb.com/manual/reference/program/mongofiles/#bin.mongofiles)and the documentation for your[driver](https://docs.mongodb.com/manual/applications/drivers/)for more information about GridFS. 138 | 139 | ### 文档字段排序 140 | 141 | MongoDB preserves the order of the document fields following write operations_except_for the following cases: 142 | 143 | * The `_id` field is always the first field in the document. 144 | * Updates that include [`renaming`](https://docs.mongodb.com/manual/reference/operator/update/rename/#up._S_rename) of 字段名称 may result in the reordering of fields in the document. 145 | 146 | Changed in version 2.6:Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the fields in a document. 147 | 148 | ### `_id` 字段 149 | 150 | 在 MongoDB 中, 存在集合中的每个文档都需要一个唯一的 [\_id](https://docs.mongodb.com/manual/reference/glossary/#term-id) 字段来作为 [主键](https://docs.mongodb.com/manual/reference/glossary/#term-primary-key). 如果一个插入的文档省略了 `_id` 字段, 那么 MongoDB 驱动会自动生成一个 [ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid) 来作为 `_id`. 151 | 152 | 这也适用于通过 [upsert: true](https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-parameter) 方式插入的文档. 153 | 154 | `_id` 字段有一下的表现和约束: 155 | 156 | * By default, MongoDB creates a unique index on the`_id`field during the creation of a collection. 157 | 158 | * The`_id`field is always the first field in the documents. If the server receives a document that does not have the`_id`field first, then the server will move the field to the beginning. 159 | 160 | * The`_id`field may contain values of any[BSON data type](https://docs.mongodb.com/manual/reference/bson-types/), other than an array. 161 | 162 | > 警告 163 | > 164 | > To ensure functioning replication, do not store values that are of the BSON regular expression type in the`_id`field. 165 | > 166 | 167 | 一下是 `_id` 的常见情况: 168 | 169 | * 使用 [ObjectId](https://docs.mongodb.com/manual/reference/bson-types/#objectid). 170 | 171 | * Use a natural unique identifier, if available. This saves space and avoids an additional index. 172 | 173 | * 生成一个自增长的数字. (译注:类似 mysql 的 auto increase) 174 | 175 | * 在你的应用中生成一个 UUID. For a more efficient storage of the UUID values in the collection and in the`_id`index, store the UUID as a value of the BSON `BinData` type. 176 | 177 | Index keys that are of the`BinData` type are more efficiently stored in the index if: 178 | 179 | * the binary subtype value is in the range of 0-7 or 128-135, and 180 | * the length of the byte array is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, or 32. 181 | 182 | * Use your driver’s BSON UUID facility to generate UUIDs. Be aware that driver implementations may implement UUID serialization and deserialization logic differently, which may not be fully compatible with other drivers. See your[driver documentation](https://api.mongodb.com/)for information concerning UUID interoperability. 183 | 184 | > NOTE 185 | > 186 | > Most MongoDB driver clients will include the`_id`field and generate an`ObjectId`before sending the insert operation to MongoDB; however, if the client sends a document without an`_id`field, the[`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)will add the`_id`field and generate the`ObjectId`. 187 | 188 | ## 文档结构的其他用途 189 | 190 | 除了定义数据记录之外, MongoDB 还可以使用文档结构来做一些, 包括但不限于: [文档查询过滤](#document-query-filter),[文档指定更新](#document-update-specification), 以及[文档索引规范](#document-index-specification) 191 | 192 | ### 文档查询过滤 193 | 194 | 查询过滤条件可以用来确定哪些记录被查询、更新、修改删除等. 195 | 196 | 你可以使用 `:` 表达式来指定匹配条件并在[查询操作](https://docs.mongodb.com/manual/reference/operator/query/)中使用. 197 | 198 | ``` 199 | { 200 | < field1 >: < value1 > , 201 | < field2 >: { < operator > : < value > }, 202 | ... 203 | } 204 | ``` 205 | 206 | 例如, 参见: 207 | 208 | * [Query Documents](https://docs.mongodb.com/manual/tutorial/query-documents/) 209 | * [Query on Embedded/Nested Documents](https://docs.mongodb.com/manual/tutorial/query-embedded-documents/) 210 | * [Query an Array](https://docs.mongodb.com/manual/tutorial/query-arrays/) 211 | * [Query an Array of Embedded Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) 212 | 213 | ### 文档指定更新 214 | 215 | 可以使用 [更新操作](https://docs.mongodb.com/manual/reference/operator/update/#id1) 来指定 [`db.collection.update()`](https://docs.mongodb.com/manual/reference/method/db.collection.update/#db.collection.update) 修改文档的具体字段. 216 | 217 | ``` 218 | { 219 | < operator1 >: { < field1 >: < value1 > , ... }, 220 | < operator2 >: { < field2 >: < value2 > , ... }, 221 | ... 222 | } 223 | ``` 224 | 225 | For examples, see[Update specifications](https://docs.mongodb.com/manual/tutorial/update-documents/#update-documents-modifiers). 226 | 227 | ### 文档索引规范 228 | 229 | 如果有设置索引的话,那么索引会定义字段的类型: 230 | 231 | ``` 232 | { < field1 >: < type1 > , < field2 >: < type2 > , ... } 233 | ``` 234 | 235 | ## 其他资源 236 | 237 | * [Thinking in Documents Part 1 \(Blog Post\)](https://www.mongodb.com/blog/post/thinking-documents-part-1?jmp=docs) 238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /introduction/extended-json.md: -------------------------------------------------------------------------------- 1 | # MongoDB Extended JSON 2 | 3 | On this page 4 | 5 | * [Parsers and Supported Format](https://docs.mongodb.com/manual/reference/mongodb-extended-json/#parsers-and-supported-format) 6 | * [BSON Data Types and Associated Representations](https://docs.mongodb.com/manual/reference/mongodb-extended-json/#bson-data-types-and-associated-representations) 7 | 8 | [JSON](https://docs.mongodb.com/manual/reference/glossary/#term-json)can only represent a subset of the types supported by[BSON](https://docs.mongodb.com/manual/reference/glossary/#term-bson). To preserve type information, MongoDB adds the following extensions to the JSON format: 9 | 10 | * _Strict mode_ 11 | . Strict mode representations of BSON types conform to the 12 | [JSON RFC](http://www.json.org/) 13 | . Any JSON parser can parse these strict mode representations as key/value pairs; however, only the MongoDB internal JSON parser recognizes the type information conveyed by the format. 14 | * `mongo` 15 | _Shell mode_ 16 | . The MongoDB internal JSON parser and the 17 | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 18 | shell can parse this mode. 19 | 20 | The representation used for the various data types depends on the context in which the JSON is parsed. 21 | 22 | ## Parsers and Supported Format 23 | 24 | ### Input in Strict Mode 25 | 26 | The following can parse representations in strict mode_with_recognition of the type information. 27 | 28 | * [REST Interfaces](https://docs.mongodb.com/ecosystem/tools/http-interfaces) 29 | * [`mongoimport`](https://docs.mongodb.com/manual/reference/program/mongoimport/#bin.mongoimport) 30 | * `--query` 31 | option of various MongoDB tools 32 | * [MongoDB Compass](https://www.mongodb.com/products/compass) 33 | 34 | Other JSON parsers, including[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell and[`db.eval()`](https://docs.mongodb.com/manual/reference/method/db.eval/#db.eval), can parse strict mode representations as key/value pairs, but_without_recognition of the type information. 35 | 36 | ### Input in`mongo`Shell Mode 37 | 38 | The following can parse representations in`mongo`shell mode_with_recognition of the type information. 39 | 40 | * [REST Interfaces](https://docs.mongodb.com/ecosystem/tools/http-interfaces) 41 | * [`mongoimport`](https://docs.mongodb.com/manual/reference/program/mongoimport/#bin.mongoimport) 42 | * `--query` 43 | option of various MongoDB tools 44 | * [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 45 | shell 46 | 47 | ### Output in Strict mode 48 | 49 | [`mongoexport`](https://docs.mongodb.com/manual/reference/program/mongoexport/#bin.mongoexport)and[REST and HTTP Interfaces](https://docs.mongodb.com/ecosystem/tools/http-interfaces)output data in_Strict mode_. 50 | 51 | ### Output in`mongo`Shell Mode 52 | 53 | [`bsondump`](https://docs.mongodb.com/manual/reference/program/bsondump/#bin.bsondump)outputs in`mongo`_Shell mode_. 54 | 55 | ## BSON Data Types and Associated Representations 56 | 57 | The following presents the BSON data types and the associated representations in_Strict mode_and`mongo`_Shell mode_. 58 | 59 | ### Binary 60 | 61 | `data_binary` 62 | 63 | 64 | 65 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 66 | | :--- | :--- | :--- | 67 | | { "$binary": "<bindata>", "$type": "<t>" } | | BinData \( <t>, <bindata> \) | 68 | 69 | * ``is the base64 representation of a binary string. 70 | * ``is a representation of a single byte indicating the data type. In 71 | _Strict mode_ 72 | it is a hexadecimal string, and in 73 | _Shell mode_ 74 | it is an integer. See the extended bson documentation. 75 | [http://bsonspec.org/spec.html](http://bsonspec.org/spec.html) 76 | 77 | ### Date 78 | 79 | `data_date` 80 | 81 | 82 | 83 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 84 | | :--- | :--- | :--- | 85 | | { "$date": "<date>" } | | new Date \( <date> \) | 86 | 87 | In_Strict mode_,``is an ISO-8601 date format with a mandatory time zone field following the template`YYYY-MM-DDTHH:mm:ss.mmm<+/-Offset>`. 88 | 89 | The MongoDB JSON parser currently does not support loading ISO-8601 strings representing dates prior to the[Unix epoch](https://docs.mongodb.com/manual/reference/glossary/#term-unix-epoch). When formatting pre-epoch dates and dates past what your system’s`time_t`type can hold, the following format is used: 90 | 91 | ``` 92 | { "$date" : { "$numberLong" : " 93 | < 94 | dateAsMilliseconds 95 | > 96 | " } } 97 | 98 | ``` 99 | 100 | In_Shell mode_,``is the JSON representation of a 64-bit signed integer giving the number of milliseconds since epoch UTC. 101 | 102 | ### Timestamp 103 | 104 | `data_timestamp` 105 | 106 | 107 | 108 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 109 | | :--- | :--- | :--- | 110 | | { "$timestamp": { "t": <t>, "i": <i> } } | | Timestamp\( <t>, <i> \) | 111 | 112 | * `<` 113 | `t` 114 | `>` 115 | is the JSON representation of a 32-bit unsigned integer for seconds since epoch. 116 | * `<` 117 | `i` 118 | `>` 119 | is a 32-bit unsigned integer for the increment. 120 | 121 | ### Regular Expression 122 | 123 | `data_regex` 124 | 125 | 126 | 127 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 128 | | :--- | :--- | :--- | 129 | | { "$regex": "<sRegex>", "$options": "<sOptions>" } | | /<jRegex>/<jOptions> | 130 | 131 | * `<` 132 | `sRegex` 133 | `>` 134 | is a string of valid JSON characters. 135 | * `<` 136 | `jRegex` 137 | `>` 138 | is a string that may contain valid JSON characters and unescaped double quote \( 139 | `"` 140 | \) characters, but may not contain unescaped forward slash \( 141 | `/` 142 | \) characters. 143 | * `<` 144 | `sOptions` 145 | `>` 146 | is a string containing the regex options represented by the letters of the alphabet. 147 | * `<` 148 | `jOptions` 149 | `>` 150 | is a string that may contain only the characters ‘g’, ‘i’, ‘m’ and ‘s’ \(added in v1.9\). Because the 151 | `JavaScript` 152 | and 153 | `mongo` 154 | `Shell` 155 | representations support a limited range of options, any nonconforming options will be dropped when converting to this representation. 156 | 157 | ### OID 158 | 159 | `data_oid` 160 | 161 | 162 | 163 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 164 | | :--- | :--- | :--- | 165 | | { "$oid": "<id>" } | | ObjectId\( "<id>" \) | 166 | 167 | ``is a 24-character hexadecimal string. 168 | 169 | ### DB Reference 170 | 171 | `data_ref` 172 | 173 | 174 | 175 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 176 | | :--- | :--- | :--- | 177 | | { "$ref": "<name>", "$id": "<id>" } | | DBRef\("<name>", "<id>"\) | 178 | 179 | * `<` 180 | `name` 181 | `>` 182 | is a string of valid JSON characters. 183 | * `<` 184 | `id` 185 | `>` 186 | is any valid extended JSON type. 187 | 188 | ### Undefined Type 189 | 190 | `data_undefined` 191 | 192 | 193 | 194 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 195 | | :--- | :--- | :--- | 196 | | { "$undefined": true } | | undefined | 197 | 198 | The representation for the JavaScript/BSON undefined type. 199 | 200 | You_cannot_use`undefined`in query documents. Consider the following document inserted into the`people`collection: 201 | 202 | ```js 203 | db.people.insert( { name : "Sally", age : undefined } ) 204 | ``` 205 | 206 | The following queries return an error: 207 | 208 | ```js 209 | db.people.find( { age : undefined } ) 210 | db.people.find( { age : { $gte : undefined } } ) 211 | ``` 212 | 213 | However, you can query for undefined values using[`$type`](https://docs.mongodb.com/manual/reference/operator/query/type/#op._S_type), as in: 214 | 215 | ```js 216 | db.people.find( { age : { $type : 6 } } ) 217 | ``` 218 | 219 | This query returns all documents for which the`age`field has value`undefined`. 220 | 221 | ### MinKey 222 | 223 | `data_minkey` 224 | 225 | 226 | 227 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 228 | | :--- | :--- | :--- | 229 | | { "$minKey": 1 } | | MinKey | 230 | 231 | The representation of the MinKey BSON data type that compares lower than all other types. See[Comparison/Sort Order](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#faq-dev-compare-order-for-bson-types)for more information on comparison order for BSON types. 232 | 233 | ### MaxKey 234 | 235 | `data_maxkey` 236 | 237 | 238 | 239 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 240 | | :--- | :--- | :--- | 241 | | { "$maxKey": 1 } | | MaxKey | 242 | 243 | The representation of the MaxKey BSON data type that compares higher than all other types. See[Comparison/Sort Order](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#faq-dev-compare-order-for-bson-types)for more information on comparison order for BSON types. 244 | 245 | ### NumberLong 246 | 247 | New in version 2.6. 248 | 249 | `data_numberlong` 250 | 251 | 252 | 253 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 254 | | :--- | :--- | :--- | 255 | | { "$numberLong": "<number>" } | | NumberLong\( "<number>" \) | 256 | 257 | `NumberLong`is a 64 bit signed integer. You must include quotation marks or it will be interpreted as a floating point number, resulting in a loss of accuracy. 258 | 259 | For example, the following commands insert`9223372036854775807`as a`NumberLong`with and without quotation marks around the integer value: 260 | 261 | ```js 262 | db.json.insert( { longQuoted : NumberLong("9223372036854775807") } ) 263 | db.json.insert( { longUnQuoted : NumberLong(9223372036854775807) } ) 264 | ``` 265 | 266 | When you retrieve the documents, the value of`longUnQuoted`has changed, while`longQuoted`retains its accuracy: 267 | 268 | ```js 269 | db.json.find() 270 | { "_id" : ObjectId("54ee1f2d33335326d70987df"), "longQuoted" : NumberLong("9223372036854775807") } 271 | { "_id" : ObjectId("54ee1f7433335326d70987e0"), "longUnQuoted" : NumberLong("-9223372036854775808") } 272 | ``` 273 | 274 | ### NumberDecimal 275 | 276 | New in version 3.4. 277 | 278 | `data_numberdecimal` 279 | 280 | 281 | 282 | | Strict Mode | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) | Shell Mode | 283 | | :--- | :--- | :--- | 284 | | { "$numberDecimal": "<number>" } | | NumberDecimal\( "<number>" \) | 285 | 286 | `NumberDecimal`is a[high-precision decimal](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst). You must include quotation marks, or the input number will be treated as a double, resulting in data loss. 287 | 288 | For example, the following commands insert`123.40`as a`NumberDecimal`with and without quotation marks around the value: 289 | 290 | ```js 291 | db.json.insert( { decimalQuoted : NumberDecimal("123.40") } ) 292 | db.json.insert( { decimalUnQuoted : NumberDecimal(123.40) } ) 293 | ``` 294 | 295 | When you retrieve the documents, the value of`decimalUnQuoted`has changed, while`decimalQuoted`retains its specified precision: 296 | 297 | ```js 298 | db.json.find() 299 | { "_id" : ObjectId("596f88b7b613bb04f80a1ea9"), "decimalQuoted" : NumberDecimal("123.40") } 300 | { "_id" : ObjectId("596f88c9b613bb04f80a1eaa"), "decimalUnQuoted" : NumberDecimal("123.400000000000") } 301 | 302 | ``` 303 | 304 | 305 | 306 | -------------------------------------------------------------------------------- /introduction/getting-started.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | [MongoDB Atlas](https://cloud.mongodb.com/?jmp=docs) 是一个定制, 运行, 监控以及维护 MongoDB 的云端服务. 它是一个快速, 简单并且免费的使用 MongoDB 的途径. 如果想在本地安装运行 MongoDB, 参见[安装 MongoDB](https://docs.mongodb.com/manual/installation/#tutorial-installation). 4 | 5 | 接下来的教程使用 [MongoDB Node.js 驱动](http://mongodb.github.io/node-mongodb-native/2.2/) 来连接一个免费的 Atlas 集群, 然后执行插入和查询操作. 6 | 7 | ## 1.创建一个 Atlas 账户. 8 | 9 | 想要使用 [MongoDB Atlas](https://cloud.mongodb.com/?jmp=docs), 请先创建你的账户并登陆到 Atlas. 10 | 11 | ## 2.创建一个 Atlas Group. 12 | 13 | 为你的 group 取个名字. 14 | 15 | ![](https://docs.mongodb.com/manual/_images/atlas-create-group.png "Screenshot of group creation prompt.") 16 | 17 | 你可以通过 gourp 来管理相关联的 MongoDB 实例. 要创建另外的 Atlas group, 请点击左上角的用户名然后选择 **My Groups**. 点击 Add Group 按钮即可. 18 | 19 | ## 3.创建一个集群. 20 | 21 | 在 Atlas 中部署一个 MongoDB 实例或者 “clusters”, 可以是一个 [replica set](https://docs.mongodb.com/manual/reference/glossary/#term-replica-set) 或者 [sharded cluster](https://docs.mongodb.com/manual/reference/glossary/#term-sharded-cluster). 22 | 23 | 要创建集群, 进入 **Clusters** 界面并点击 **Add New Cluster** 或者 **Build a New Cluster** 按钮. 24 | 25 | ![](https://docs.mongodb.com/manual/_images/atlas-create-cluster.png "Screenshot of cluster config options during creation.") 26 | 27 | 1. 输入 Cluster Name. 28 | 29 | 2. 找到 M0 级免费教学实例, 并点击对应的 Select 按钮. 30 | 31 | 3. 输入 Username (用户名) 和 Password (密码). 32 | 33 | ![](https://docs.mongodb.com/manual/_images/atlas-create-cluster-add-user.png "Screenshot of admin username and password fields that appear only when admin user doesn't exist.") 34 | These fields appear only if no MongoDB user exists for your Atlas group. If you created users in the group beforehand these fields will not appear. 35 | 36 | 4. 点击 Confirm & Deploy (确认部署). 37 | 38 | ## 4.安全设置 39 | 40 | Atlas 只允许 group 入口白名单中的客户端连接集群. 在白名单中添加一个入口: 41 | 42 | ![](https://docs.mongodb.com/manual/_images/atlas-setup-cluster-security.png "Screeenshot of cluster security tab on Atlas.") 43 | 44 | 1. 在 Clusters 页面点击 Security 选项. 45 | 2. 点击 IP Whitelist, 然后添加 IP Address. 你可以在 Whitelist Entry 中手动输入 IP 地址, 也可以点击 Add Current IP Address 按钮. 46 | 3. 点击 Confirm 然后等待 Atlas 更新防火墙. 47 | 48 | ## 5.下载驱动客户端. 49 | 50 | 推荐通过 `npm init` 初始化一个项目的配置文件, 然后用 `npm` 安装 [MongoDB Node.js 驱动](http://mongodb.github.io/node-mongodb-native/2.2/): 51 | 52 | ``` 53 | npm install mongodb --save 54 | ``` 55 | 56 | 需要更多信息, 请查看 Node.js 驱动[快速开始](http://mongodb.github.io/node-mongodb-native/2.2/installation-guide/installation-guide/)文档. 57 | 58 | ## 6.获取 URI 连接串. 59 | 60 | 通过 MongoDB Atlas Clusters 页面: 61 | 62 | 1. 点击 Connect 按钮来查看 [URI 连接字符串](https://docs.mongodb.com/manual/reference/connection-string/#mongodb-uri). 63 | 2. 复制连接字符串. 64 | 3. 将连接串中的 `` 替换成之前创建时设置的密码, 并且替换 65 | `` 为你要连接/简历的数据库名. 下文中使用 `test` 数据库. 66 | 4. 复制修改好的 URI. 67 | 68 | ## 7.连接到集群 69 | 70 | 使用上一步获取的 **URI 字符串**, 连接 Atlas 集群: 71 | 72 | ```js 73 | var MongoClient = require('mongodb').MongoClient; 74 | 75 | var uri = "mongodb://user123:p455w0rd@gettingstarted-shard-00-00-hyjsm.mongodb.net:27017,gettingstarted-shard-00-01-hyjsm.mongodb.net:27017,gettingstarted-shard-00-02-hyjsm.mongodb.net:27017/test?ssl=true&replicaSet=GettingStarted-shard-0&authSource=admin"; 76 | MongoClient.connect(uri, function(err, db) { 77 | // Paste the following examples here 78 | 79 | db.close(); 80 | }); 81 | ``` 82 | 83 | ## 文档 & 集合 84 | 85 | MongoDB 在 [collections](https://docs.mongodb.com/manual/reference/glossary/#term-collection) 中使用 [BSON 结构](https://docs.mongodb.com/manual/core/document/#bson-document-format)\(二进制格式的 JSON\) 来存储数据. MongoDB 中一个数据库对应多个集合, 一个集合对应多个文档. 86 | 87 | ## 插入文档 88 | 89 | [Collection.insertMany\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) 可以用来插入 _多个_ [文档](https://docs.mongodb.com/manual/core/document/#bson-document-format). 传递一个包含文档的给这个方法. 90 | 91 | 如下代码插入了新的文档到 `inventory` 集合中: 92 | 93 | 94 | ```js 95 | db.collection('inventory').insertMany([ 96 | // MongoDB adds the _id field with an ObjectId if _id is not present 97 | { item: "journal", qty: 25, status: "A", 98 | size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] }, 99 | { item: "notebook", qty: 50, status: "A", 100 | size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] }, 101 | { item: "paper", qty: 100, status: "D", 102 | size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] }, 103 | { item: "planner", qty: 75, status: "D", 104 | size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] }, 105 | { item: "postcard", qty: 45, status: "A", 106 | size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] } 107 | ]) 108 | .then(function(result) { 109 | // process result 110 | }) 111 | ``` 112 | 113 | [insertMany\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) 返回一个包含被插入文档的 `_id` 的数据. 可以查看[这里](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#insertmany-examples)的例子. 114 | 115 | 使用 [Collection.insertOne\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertOne) 来插入单个文档. 116 | 117 | 想要更多的文档和例子, 可以参见[增删改查](/crud/)章节的[插入](/crud/insert.html). 118 | 119 | ## Query 120 | 121 | ### 查询所有 122 | 123 | 要查询 (select) 所有集合中的文档, 给 [Collection.find\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find) 方法传一个空的文档作为[查询过滤](https://docs.mongodb.com/manual/core/document/#document-query-filter): 124 | 125 | 126 | ```js 127 | var cursor = db.collection('inventory').find({}); 128 | ``` 129 | 130 | 要查询匹配指定条件的文档, 可以使用 [find\(\)](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find) 方法, 并传递 `<字段>:<值>` 格式的[过滤](https://docs.mongodb.com/manual/core/document/#document-query-filter) 条件. 下例为查询 `inventory` 集合中所有的 `status` 为 `"D"` 的文档: 131 | 132 | 133 | ```js 134 | var cursor = db.collection('inventory').find({ status: "D" }); 135 | ``` 136 | 137 | ### 匹配嵌套内容 138 | 139 | 相等的匹配在匹配整个嵌套结构的文档时需要 _确切_ 地指定 ``, 包括字段的顺序. 举个栗子, 下列语句可以查询所有 `size` 字段等于 `{h:14,w:21,uom:"cm"}` 的文档: 140 | 141 | 142 | ```js 143 | var cursor = db.collection('inventory').find({ 144 | size: { h: 14, w: 21, uom: "cm" } 145 | }); 146 | ``` 147 | 148 | ### 匹配嵌套文档中的一个字段 149 | 150 | 查询所有嵌套在 `size` 字段下的 `uom` 字段等于 `"in"` 的文档: 151 | 152 | ```js 153 | var cursor = db.collection('inventory').find({ 154 | "size.uom": "in" 155 | }); 156 | ``` 157 | 158 | ### 匹配数组中的一个元素 159 | 160 | 查询 `tags` 是一个数组并且其中包含 `"red"` 的所有文档: 161 | 162 | ```js 163 | var cursor = db.collection('inventory').find({ 164 | tags: "red" 165 | }); 166 | ``` 167 | 168 | ### 精确匹配一个数组 169 | 170 | 查询 `tags` 字段的值为一个包含 `"red"` 和 `"blank"` 并且顺序确定的数组的所有文档: 171 | 172 | 173 | ```js 174 | var cursor = db.collection('inventory').find({ 175 | tags: [ "red", "blank" ] 176 | }); 177 | ``` 178 | 179 | 更多信息以及查询例子, 参见[增删改查](https://docs.mongodb.com/manual/crud/#crud)章节的[查询](https://docs.mongodb.com/manual/tutorial/query-documents/#read-operations-queries). 180 | 181 | 关于更新和删除文档, 参见[Update Documents](https://docs.mongodb.com/manual/tutorial/update-documents/#write-op-update)和[Delete Documents](https://docs.mongodb.com/manual/tutorial/remove-documents/#write-op-delete). 182 | 183 | ## 下一步 184 | 185 | 当你阅读完 Getting Started 概览之后, 你可以通过下列课程和主题获得更多帮助: 186 | 187 | 想学习更多关于 MongoDB 查询语句和其他 MongoDB 基础知识, 可以注册 [M001: MongoDB Basics](https://university.mongodb.com/courses/M001/about) 课程. 188 | 189 | | Introduction | Developers | Administrators | Reference | 190 | | :--- | :--- | :--- | :--- | 191 | | [MongoDB 简介](/introduction/)
[安装指南](https://docs.mongodb.com/manual/installation/)
[数据库 & 集合](/introduction/db-and-collections.html)
[文档](/introduction/document.html) | [增删改查](http://localhost:4000/crud/)
[聚合](http://localhost:4000/aggregation/)
[SQL 转 MongoDB](https://docs.mongodb.com/manual/reference/sql-comparison/)
[索引](https://docs.mongodb.com/manual/indexes/) | [Production Notes](https://docs.mongodb.com/manual/administration/production-notes/)
[复制集](https://docs.mongodb.com/manual/replication/)
[Sharded 集群](https://docs.mongodb.com/manual/sharding/)
[MongoDB 安全](https://docs.mongodb.com/manual/security/) | [Shell 方法](https://docs.mongodb.com/manual/reference/method/)
[查询操作符](https://docs.mongodb.com/manual/reference/operator/)
[Reference](https://docs.mongodb.com/manual/reference/)
[术语表](/reference/glossary.html) | 192 | 193 | 194 | 195 | -------------------------------------------------------------------------------- /introduction/views.md: -------------------------------------------------------------------------------- 1 | # 视图 2 | 3 | _3.4 版本新功能_ 4 | 5 | 本页索引 6 | 7 | * [创建视图](https://docs.mongodb.com/manual/core/views/#创建视图) 8 | * [表现](https://docs.mongodb.com/manual/core/views/#表现) 9 | * [删除视图](https://docs.mongodb.com/manual/core/views/#删除视图) 10 | * [修改视图](https://docs.mongodb.com/manual/core/views/#修改视图) 11 | * [支持操作](https://docs.mongodb.com/manual/core/views/#支持操作) 12 | 13 | 从 3.4 开始, MongoDB 添加了基于已存在的集合或者 View (视图) 创建只读的 View 支持. 14 | 15 | ## 创建视图 16 | 17 | 创建或者定义一个视图, MongoDB 3.4 的介绍是: 18 | 19 | * the `viewOn` and `pipeline`options to the existing[`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create)command \(and[`db.createCollection`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)helper\): 20 | 21 | ``` 22 | db.runCommand( { create: , viewOn: , pipeline: } ) 23 | ``` 24 | 25 | or if specifying a default[collation](https://docs.mongodb.com/manual/release-notes/3.4/#relnotes-collation)for the view: 26 | 27 | ``` 28 | db.runCommand( { create: , viewOn: , pipeline: , collation: } ) 29 | ``` 30 | 31 | * a new[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell helper[`db.createView()`](https://docs.mongodb.com/manual/reference/method/db.createView/#db.createView): 32 | 33 | ``` 34 | db.createView(, , , ) 35 | ``` 36 | 37 | ## 表现 38 | 39 | 视图具备以下几种表现: 40 | 41 | ### 只读 42 | 43 | 视图是只读的; 通过视图进行写操作会报错. 44 | 45 | 以下为支持视图的读操作: 46 | 47 | * [`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find) 48 | * [`db.collection.findOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.findOne/#db.collection.findOne) 49 | * [`db.collection.aggregate()`](https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/#db.collection.aggregate) 50 | * [`db.collection.count()`](https://docs.mongodb.com/manual/reference/method/db.collection.count/#db.collection.count) 51 | * [`db.collection.distinct()`](https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#db.collection.distinct) 52 | 53 | ### 索引使用 & 排序操作 54 | 55 | * 视图使用其上游集合的索引. 56 | 57 | * 由于索引是基于集合的, 所以你不能基于视图创建, 删除或重建索引, 也不能获取视图的索引列表. 58 | 59 | * 你不能指定 [`$natural`](https://docs.mongodb.com/manual/reference/operator/meta/natural/#metaOp._S_natural) 排序. 60 | 61 | 例如, 下列操作是 _错误的_: 62 | 63 | ``` 64 | db.view.find().sort({$natural: 1}) 65 | ``` 66 | 67 | ### Project 限制 68 | 69 | 视图上的 [`find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find) 方法不支持如下[projection](https://docs.mongodb.com/manual/reference/operator/projection/) 操作: 70 | 71 | * [`$`](https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_) 72 | * [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch) 73 | * [`$slice`](https://docs.mongodb.com/manual/reference/operator/projection/slice/#proj._S_slice) 74 | * [`$meta`](https://docs.mongodb.com/manual/reference/operator/projection/meta/#proj._S_meta) 75 | 76 | ### 不能改变名称 77 | 78 | 你不能重命名[视图](#). 79 | 80 | ### 视图创建 81 | 82 | * 视图是在读操邹期间根据需要实时计算的, 同时 MongoDB 基于视图的读操作是底层聚合管道 (aggregation pipeline) 的一部分. 因此, 视图不支持一下操作: 83 | * [`db.collection.mapReduce()`](https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/#db.collection.mapReduce), 84 | * [`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text) 操作, 因为 `$text` 只在聚合的第一阶段有效, 85 | * [`geoNear`](https://docs.mongodb.com/manual/reference/command/geoNear/#dbcmd.geoNear) 命令和 [`$geoNear`](https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear) 86 | 管道阶段. 87 | * 如果用于创建视图的聚合管道屏蔽了 `_id` 字段, 那么视图中的文档也会没有 `_id` 字段. 88 | 89 | ### 分片视图 90 | 91 | 如果视图依赖的集合是分片的, 那么视图也视为分片的. 因此, 你不能指定分片视图中 [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup) 的 `from`字段与 [`$graphLookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup) 操作. 92 | 93 | ### Views 与 Collation 94 | 95 | * You can specify a default [collation](https://docs.mongodb.com/manual/reference/collation/) for a view at creation time. If no collation is specified, the view’s default collation is the “simple” binary comparison collator. That is, the view does not inherit the collection’s default collation. 96 | * String comparisons on the view use the view’s default collation. An operation that attempts to change or override a view’s default collation will fail with an error. 97 | * If creating a view from another view, you cannot specify a collation that differs from the source view’s collation. 98 | * If performing an aggregation that involves multiple views, such as with [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup) or [`$graphLookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup) , the views must have the same [collation](https://docs.mongodb.com/manual/reference/collation/). 99 | 100 | ### 公共视图定义 101 | 102 | 列出集合的操作, 如 [`db.getCollectionInfos()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/#db.getCollectionInfos) 和 [`db.getCollectionNames()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/#db.getCollectionNames), 的结果中会包括它们的视图. 103 | 104 | > IMPORTANT 105 | > 106 | > 视图定义是公开的; 即在视图上的 [`db.getCollectionInfos()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/#db.getCollectionInfos) 和 `explain` 操作将会包括定义视图的管道. 因此, 请避免直接引用视图定义中敏感的字段和值. 107 | > 108 | 109 | ## 删除视图 110 | 111 | 要删除视图, 请使用视图上的 [`db.collection.drop()`](https://docs.mongodb.com/manual/reference/method/db.collection.drop/#db.collection.drop) 方法. 112 | 113 | ## 修改视图 114 | 115 | 你可以通过删除或者重建的方式修改视图, 也可以使用 [`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod) 命令. 116 | 117 | ## 支持操作 118 | 119 | 以下操作支持视图, 除了本文中提到的限制除外: 120 | 121 | | 命令 | 方法 | 122 | | :--- | :--- | 123 | | [`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create) | [`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)
[`db.createView()`](https://docs.mongodb.com/manual/reference/method/db.createView/#db.createView) | 124 | | [`collMod`](https://docs.mongodb.com/manual/reference/command/collMod/#dbcmd.collMod) | | 125 | | | [`db.getCollection()`](https://docs.mongodb.com/manual/reference/method/db.getCollection/#db.getCollection)
[`db.getCollectionInfos()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/#db.getCollectionInfos)
[`db.getCollectionNames()`](https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/#db.getCollectionNames) | 126 | | [`find`](https://docs.mongodb.com/manual/reference/command/find/#dbcmd.find)
[`distinct`](https://docs.mongodb.com/manual/reference/command/distinct/#dbcmd.distinct)
[`count`](https://docs.mongodb.com/manual/reference/command/count/#dbcmd.count) | [`db.collection.aggregate()`](https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/#db.collection.aggregate)
[`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)
[`db.collection.findOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.findOne/#db.collection.findOne)
[`db.collection.count()`](https://docs.mongodb.com/manual/reference/method/db.collection.count/#db.collection.count)
[`db.collection.distinct()`](https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#db.collection.distinct) | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /reference/collation.md: -------------------------------------------------------------------------------- 1 | # Collation 2 | 3 | On this page 4 | 5 | * [文档结构](#文档结构) 6 | * [支持核对的操作](#支持核对的操作) 7 | * [表现](#表现) 8 | 9 | 3.4 版本中的新功能. 10 | 11 | 核对 (Collation) 允许用户来指定一个特定语言规则的字符串比较, 比如小写字母和口音标记的规则。 12 | 13 | 你可以为集合、视图或者索引指定核对,也可以给特定的支持核对操作的方法来指定核对。 14 | 15 | ## 文档结构 16 | 17 | 一个核对的文档结构有以下一些字段: 18 | 19 | ``` 20 | { 21 | locale: , 22 | caseLevel: , 23 | caseFirst: , 24 | strength: , 25 | numericOrdering: , 26 | alternate: , 27 | maxVariable: , 28 | backwards: 29 | } 30 | ``` 31 | 32 | 当指定了核对, `locale` 字段就是强制要带上的; 所有其他的字段都是可选的。关于这些字段的描述,参见 [Collation Document](#collation-document-fields)。 33 | 34 | 默认的核对规则参数根据你指定的 `locale` 字段而不同。关于完整的默认核对参数列表以及它们相关的 `locale`,参见 [Collation Default Parameters](https://docs.mongodb.com/manual/reference/collation-locales-defaults/#collation-default-params). 35 | 36 | | Field | Type | Description | 37 | | :--- | :--- | :--- | 38 | | `locale` | string | The ICU locale. See [Supported Languages and Locales](https://docs.mongodb.com/manual/reference/collation-locales-defaults/#collation-languages-locales) for a list of supported locales.
To specify simple binary comparison, specify `locale` value of `"simple"`. | 39 | | `strength` | integer | 可选。指定比较的等级。相当于 [ICU 比较等级](http://userguide.icu-project.org/collation/concepts#TOC-Comparison-Levels)。可能的值:
描述描述
1Primary 等级的比较。核对过程仅执行基本角色的比较,忽略其他的不同例如 diacritics and case。
2Secondary 等级的比较。 Collation performs comparisons up to secondary differences, such as diacritics. That is, collation performs comparisons of base characters \(primary differences\) and diacritics \(secondary differences\). Differences between base characters takes precedence over secondary differences.
3Tertiary 等级的比较。 Collation performs comparisons up to tertiary differences, such as case and letter variants. That is, collation performs comparisons of base characters \(primary differences\), diacritics \(secondary differences\), and case and variants \(tertiary differences\). Differences between base characters takes precedence over secondary differences, which takes precedence over tertiary differences.This is the default level.
4Quaternary Level. Limited for specific use case to consider punctuation when levels 1-3 ignore punctuation or for processing Japanese text.
5Identical Level. Limited for specific use case of tie breaker.See[ICU Collation: Comparison Levels](http://userguide.icu-project.org/collation/concepts#TOC-Comparison-Levels)for details.
| 40 | | `caseLevel` | boolean | 可选。 Flag that determines whether to include case comparison at `strength` level `1` or`2`.If`true`, include case comparison; i.e.When used with`strength:1`, collation compares base characters and case.When used with`strength:2`, collation compares base characters, diacritics \(and possible other secondary differences\) and case.If`false`, do not include case comparison at level `1` or`2`. The default is`false`.For more information, see[ICU Collation: Case Level](http://userguide.icu-project.org/collation/concepts#TOC-CaseLevel). | 41 | | `caseFirst` | string | 可选。 A flag that determines sort order of case differences during tertiary level comparisons.Possible values are:
ValueDescription
“upper”Uppercase sorts before lowercase.
“lower”Lowercase sorts before uppercase.
“off”Default value. Similar to`"lower"`with slight differences. See[http://userguide.icu-project.org/collation/customization](http://userguide.icu-project.org/collation/customization)for details of differences.
| 42 | | `numericOrdering` | boolean | 可选。 Flag that determines whether to compare numeric strings as numbers or as strings.If`true`, compare as numbers; i.e.`"10"`is greater than`"2"`.If`false`, compare as strings; i.e.`"10"`is less than`"2"`.Default is`false`. | 43 | | `alternate` | string | 可选。 Field that determines whether collation should consider whitespace and punctuation as base characters for purposes of comparison.Possible values are:ValueDescription`"non-ignorable"`Whitespace and punctuation are considered base characters.`"shifted"`Whitespace and punctuation are not considered base characters and are only distinguished at strength levels greater than 3.See[ICU Collation: Comparison Levels](http://userguide.icu-project.org/collation/concepts#TOC-Comparison-Levels)for more information.Default is`"non-ignorable"`. | 44 | | `maxVariable` | string | 可选。 Field that determines up to which characters are considered ignorable when`alternate:"shifted"`. Has no effect if`alternate:"non-ignorable"`Possible values are:ValueDescription`"punct"`Both whitespaces and punctuation are “ignorable”, i.e. not considered base characters.`"space"`Whitespace are “ignorable”, i.e. not considered base characters. | 45 | | `backwards` | boolean | 可选。 Flag that determines whether strings with diacritics sort from back of the string, such as with some French dictionary ordering.If`true`, compare from back to front.If`false`, compare from front to back.The default value is`false`. | 46 | | `normalization` | boolean | 可选。 Flag that determines whether to check if text require normalization and to perform normalization. Generally, majority of text does not require this normalization processing.If`true`, check if fully normalized and perform normaliztion to compare text.If`false`, does not check.The default value is`false`.See[http://userguide.icu-project.org/collation/concepts\#TOC-Normalization](http://userguide.icu-project.org/collation/concepts#TOC-Normalization)for details. | 47 | 48 | ## 支持核对的操作 49 | 50 | You can specify collation for the following operations: 51 | 52 | NOTE 53 | 54 | You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort. 55 | 56 | | Commands | `mongo` | Shell Methods | 57 | | :--- | :--- | :--- | 58 | | | [`create`](https://docs.mongodb.com/manual/reference/command/create/#dbcmd.create) | [`db.createCollection()`](https://docs.mongodb.com/manual/reference/method/db.createCollection/#db.createCollection)[`db.createView()`](https://docs.mongodb.com/manual/reference/method/db.createView/#db.createView) | 59 | | | [`createIndexes`](https://docs.mongodb.com/manual/reference/command/createIndexes/#dbcmd.createIndexes) | [`db.collection.createIndex()`](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex) | 60 | | | [`aggregate`](https://docs.mongodb.com/manual/reference/command/aggregate/#dbcmd.aggregate) | [`db.collection.aggregate()`](https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/#db.collection.aggregate) | 61 | | | [`distinct`](https://docs.mongodb.com/manual/reference/command/distinct/#dbcmd.distinct) | [`db.collection.distinct()`](https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#db.collection.distinct) | 62 | | | [`findAndModify`](https://docs.mongodb.com/manual/reference/command/findAndModify/#dbcmd.findAndModify) | [`db.collection.findAndModify()`](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#db.collection.findAndModify)[`db.collection.findOneAndDelete()`](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/#db.collection.findOneAndDelete)[`db.collection.findOneAndReplace()`](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/#db.collection.findOneAndReplace)[`db.collection.findOneAndUpdate()`](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/#db.collection.findOneAndUpdate) | 63 | | | [`find`](https://docs.mongodb.com/manual/reference/command/find/#dbcmd.find) | [`cursor.collation()`](https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation)to specify collation for[`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find) | 64 | | | [`mapReduce`](https://docs.mongodb.com/manual/reference/command/mapReduce/#dbcmd.mapReduce) | [`db.collection.mapReduce()`](https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/#db.collection.mapReduce) | 65 | | | [`delete`](https://docs.mongodb.com/manual/reference/command/delete/#dbcmd.delete) | [`db.collection.deleteOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/#db.collection.deleteOne)[`db.collection.deleteMany()`](https://docs.mongodb.com/manual/reference/method/db.collection.deleteMany/#db.collection.deleteMany)[`db.collection.remove()`](https://docs.mongodb.com/manual/reference/method/db.collection.remove/#db.collection.remove) | 66 | | | [`update`](https://docs.mongodb.com/manual/reference/command/update/#dbcmd.update) | [`db.collection.update()`](https://docs.mongodb.com/manual/reference/method/db.collection.update/#db.collection.update)[`db.collection.updateOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#db.collection.updateOne),[`db.collection.updateMany()`](https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#db.collection.updateMany),[`db.collection.replaceOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/#db.collection.replaceOne) | 67 | | | [`shardCollection`](https://docs.mongodb.com/manual/reference/command/shardCollection/#dbcmd.shardCollection) | [`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection) | 68 | | | | Individual update, replace, and delete operations in[`db.collection.bulkWrite()`](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite). | 69 | 70 | ## 表现 71 | 72 | ### Local Variants 73 | 74 | Some collation locales have variants, which employ special language-specific rules. To specify a locale variant, use the following syntax: 75 | 76 | ``` 77 | { "locale" : "@collation=" } 78 | ``` 79 | 80 | For example, to use the `pinyin` variant of the Chinese collation: 81 | 82 | ``` 83 | { "locale" : "zh@collation=pinyin" } 84 | ``` 85 | 86 | For a complete list of all collation locales and their variants, see[Collation Locales](https://docs.mongodb.com/manual/reference/collation-locales-defaults/#collation-languages-locales). 87 | 88 | ### Collation and Views 89 | 90 | * You can specify a default 91 | [collation](#) 92 | for a view at creation time. If no collation is specified, the view’s default collation is the “simple” binary comparison collator. That is, the view does not inherit the collection’s default collation. 93 | * String comparisons on the view use the view’s default collation. An operation that attempts to change or override a view’s default collation will fail with an error. 94 | * If creating a view from another view, you cannot specify a collation that differs from the source view’s collation. 95 | * If performing an aggregation that involves multiple views, such as with 96 | [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#pipe._S_lookup) 97 | or 98 | [`$graphLookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup) 99 | , the views must have the same 100 | [collation](#) 101 | . 102 | 103 | ### Collation and Index Use 104 | 105 | To use an index for string comparisons, an operation must also specify the same collation. That is, an index with a collation cannot support an operation that performs string comparisons on the indexed fields if the operation specifies a different collation. 106 | 107 | For example, the collection `myColl` has an index on a string field `category` with the collation locale`"fr"`. 108 | 109 | ``` 110 | db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } ) 111 | ``` 112 | 113 | The following query operation, which specifies the same collation as the index, can use the index: 114 | 115 | ``` 116 | db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } ) 117 | ``` 118 | 119 | However, the following query operation, which by default uses the “simple” binary collator, cannot use the index: 120 | 121 | ``` 122 | db.myColl.find( { category: "cafe" } ) 123 | ``` 124 | 125 | For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys. 126 | 127 | For example, the collection `myColl` has a compound index on the numeric fields `score` and `price` and the string field`category`; the index is created with the collation locale`"fr"`for string comparisons: 128 | 129 | ``` 130 | db.myColl.createIndex( 131 | { score: 1, price: 1, category: 1 }, 132 | { collation: { locale: "fr" } } ) 133 | ``` 134 | 135 | The following operations, which use`"simple"`binary collation for string comparisons, can use the index: 136 | 137 | ``` 138 | db.myColl.find( { score: 5 } ).sort( { price: 1 } ) 139 | db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } ) 140 | ``` 141 | 142 | The following operation, which uses`"simple"`binary collation for string comparisons on the indexed `category` field, can use the index to fulfill only the`score:5`portion of the query: 143 | 144 | ``` 145 | db.myColl.find( { score: 5, category: "cafe" } ) 146 | ``` 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /reference/glossary.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ElemeFE/mongodb-doc-cn/c7c6e7167f498ad0a99da50af32897baa84b7f2b/reference/glossary.md -------------------------------------------------------------------------------- /reference/operators/query-and-project.md: -------------------------------------------------------------------------------- 1 | # Query and Projection Operators 2 | 3 | On this page 4 | 5 | * [Query Selectors](https://docs.mongodb.com/manual/reference/operator/query/#query-selectors) 6 | * [Projection Operators](https://docs.mongodb.com/manual/reference/operator/query/#projection-operators) 7 | * [Additional Resources](https://docs.mongodb.com/manual/reference/operator/query/#additional-resources) 8 | 9 | NOTE 10 | 11 | For details on specific operator, including syntax and examples, click on the specific operator to go to its reference page. 12 | 13 | ## Query Selectors 14 | 15 | ### Comparison 16 | 17 | For comparison of different BSON type values, see the[specified BSON comparison order](https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#bson-types-comparison-order). 18 | 19 | | Name | Description | 20 | | :--- | :--- | 21 | | [`$eq`](https://docs.mongodb.com/manual/reference/operator/query/eq/#op._S_eq) | Matches values that are equal to a specified value. | 22 | | [`$gt`](https://docs.mongodb.com/manual/reference/operator/query/gt/#op._S_gt) | Matches values that are greater than a specified value. | 23 | | [`$gte`](https://docs.mongodb.com/manual/reference/operator/query/gte/#op._S_gte) | Matches values that are greater than or equal to a specified value. | 24 | | [`$in`](https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in) | Matches any of the values specified in an array. | 25 | | [`$lt`](https://docs.mongodb.com/manual/reference/operator/query/lt/#op._S_lt) | Matches values that are less than a specified value. | 26 | | [`$lte`](https://docs.mongodb.com/manual/reference/operator/query/lte/#op._S_lte) | Matches values that are less than or equal to a specified value. | 27 | | [`$ne`](https://docs.mongodb.com/manual/reference/operator/query/ne/#op._S_ne) | Matches all values that are not equal to a specified value. | 28 | | [`$nin`](https://docs.mongodb.com/manual/reference/operator/query/nin/#op._S_nin) | Matches none of the values specified in an array. | 29 | 30 | ### Logical 31 | 32 | | Name | Description | 33 | | :--- | :--- | 34 | | [`$and`](https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and) | Joins query clauses with a logical`AND`returns all documents that match the conditions of both clauses. | 35 | | [`$not`](https://docs.mongodb.com/manual/reference/operator/query/not/#op._S_not) | Inverts the effect of a query expression and returns documents that do_not_match the query expression. | 36 | | [`$nor`](https://docs.mongodb.com/manual/reference/operator/query/nor/#op._S_nor) | Joins query clauses with a logical`NOR`returns all documents that fail to match both clauses. | 37 | | [`$or`](https://docs.mongodb.com/manual/reference/operator/query/or/#op._S_or) | Joins query clauses with a logical`OR`returns all documents that match the conditions of either clause. | 38 | 39 | ### Element 40 | 41 | | Name | Description | 42 | | :--- | :--- | 43 | | [`$exists`](https://docs.mongodb.com/manual/reference/operator/query/exists/#op._S_exists) | Matches documents that have the specified field. | 44 | | [`$type`](https://docs.mongodb.com/manual/reference/operator/query/type/#op._S_type) | Selects documents if a field is of the specified type. | 45 | 46 | ### Evaluation 47 | 48 | | Name | Description | 49 | | :--- | :--- | 50 | | [`$mod`](https://docs.mongodb.com/manual/reference/operator/query/mod/#op._S_mod) | Performs a modulo operation on the value of a field and selects documents with a specified result. | 51 | | [`$regex`](https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex) | Selects documents where values match a specified regular expression. | 52 | | [`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text) | Performs text search. | 53 | | [`$where`](https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where) | Matches documents that satisfy a JavaScript expression. | 54 | 55 | ### Geospatial 56 | 57 | | Name | Description | 58 | | :--- | :--- | 59 | | [`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects) | Selects geometries that intersect with a[GeoJSON](https://docs.mongodb.com/manual/reference/glossary/#term-geojson)geometry. The[2dsphere](https://docs.mongodb.com/manual/core/2dsphere/)index supports[`$geoIntersects`](https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects). | 60 | | [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin) | Selects geometries within a bounding[GeoJSON geometry](https://docs.mongodb.com/manual/reference/geojson/#geospatial-indexes-store-geojson). The[2dsphere](https://docs.mongodb.com/manual/core/2dsphere/)and[2d](https://docs.mongodb.com/manual/core/2d/)indexes support[`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin). | 61 | | [`$near`](https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near) | Returns geospatial objects in proximity to a point. Requires a geospatial index. The[2dsphere](https://docs.mongodb.com/manual/core/2dsphere/)and[2d](https://docs.mongodb.com/manual/core/2d/)indexes support[`$near`](https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near). | 62 | | [`$nearSphere`](https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere) | Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The[2dsphere](https://docs.mongodb.com/manual/core/2dsphere/)and[2d](https://docs.mongodb.com/manual/core/2d/)indexes support[`$nearSphere`](https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere). | 63 | 64 | ### Array 65 | 66 | | Name | Description | 67 | | :--- | :--- | 68 | | [`$all`](https://docs.mongodb.com/manual/reference/operator/query/all/#op._S_all) | Matches arrays that contain all elements specified in the query. | 69 | | [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch) | Selects documents if element in the array field matches all the specified[`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch)conditions. | 70 | | [`$size`](https://docs.mongodb.com/manual/reference/operator/query/size/#op._S_size) | Selects documents if the array field is a specified size. | 71 | 72 | ### Bitwise 73 | 74 | | Name | Description | 75 | | :--- | :--- | 76 | | [`$bitsAllClear`](https://docs.mongodb.com/manual/reference/operator/query/bitsAllClear/#op._S_bitsAllClear) | Matches numeric or binary values in which a set of bit positions_all_have a value of`0`. | 77 | | [`$bitsAllSet`](https://docs.mongodb.com/manual/reference/operator/query/bitsAllSet/#op._S_bitsAllSet) | Matches numeric or binary values in which a set of bit positions_all_have a value of`1`. | 78 | | [`$bitsAnyClear`](https://docs.mongodb.com/manual/reference/operator/query/bitsAnyClear/#op._S_bitsAnyClear) | Matches numeric or binary values in which_any_bit from a set of bit positions has a value of`0`. | 79 | | [`$bitsAnySet`](https://docs.mongodb.com/manual/reference/operator/query/bitsAnySet/#op._S_bitsAnySet) | Matches numeric or binary values in which_any_bit from a set of bit positions has a value of`1`. | 80 | 81 | ### Comments 82 | 83 | | Name | Description | 84 | | :--- | :--- | 85 | | [`$comment`](https://docs.mongodb.com/manual/reference/operator/query/comment/#op._S_comment) | Adds a comment to a query predicate. | 86 | 87 | ## Projection Operators 88 | 89 | | Name | Description | 90 | | :--- | :--- | 91 | | [`$`](https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_) | Projects the first element in an array that matches the query condition. | 92 | | [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch) | Projects the first element in an array that matches the specified[`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch)condition. | 93 | | [`$meta`](https://docs.mongodb.com/manual/reference/operator/projection/meta/#proj._S_meta) | Projects the document’s score assigned during[`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text)operation. | 94 | | [`$slice`](https://docs.mongodb.com/manual/reference/operator/projection/slice/#proj._S_slice) | Limits the number of elements projected from an array. Supports skip and limit slices. | 95 | 96 | ## Additional Resources 97 | 98 | * [Quick Reference Cards](https://www.mongodb.com/lp/misc/quick-reference-cards?jmp=docs) 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /replication/README.md: -------------------------------------------------------------------------------- 1 | # Replication 2 | 3 | 本页索引 4 | 5 | * [冗余和数据可用性](#冗余和数据可用性) 6 | * [MongoDB 的复制](#mongodb-的复制) 7 | * [异步复制](#异步复制) 8 | * [自动熔断](#自动熔断) 9 | * [读操作](#读操作) 10 | * [附加特性](#附加特性) 11 | 12 | MongoDB 的 _复制集_ 是一组维护同样数据的 [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)进程实例. 复制集提供了冗余和高可用性, 是所有生产部署的基础. 本节介绍 MongoDB 中的复制以及复制集的组件和体系结构. 本节还提供与副本集相关的常见任务的教程. 13 | 14 | ## 冗余和数据可用性 15 | 16 | 复制提供冗余并增加数据可用性. 在不同数据库服务器上有多个数据副本的情况下, 复制可以提供一定的容错能力, 以防止单个节点的数据丢失. 17 | 18 | 在某些情况下, 复制可以提高读取能力, 因为客户端可以将读取操作发送到不同的服务器. 在不同的数据中心中维护数据副本可以提高分布式应用程序的数据本地化和可用性. 您也可以为了专门目的而保留其他副本, 例如灾难恢复, 报告或备份. 19 | 20 | ## MongoDB 的复制 21 | 22 | 副本集是维护同样数据的一组 [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod) 实例. 副本集包含多个数据承载节点和可选的一个仲裁节点. 在数据承载节点中, 只有一个成员被认为是主节点, 而其他节点被认为是从节点. 23 | 24 | [主节点](https://docs.mongodb.com/manual/core/replica-set-primary/)接收所有的写操作. 一个副本集只能有一个主节点来确通过 [`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern. "majority") 确认写操作; 尽管在某些情况下, 另一个 mongod 实例可能暂时认为自己也是主节点. [\[1\]](#edge-cases-2-primaries) 主节点会将所有的数据变化记录在它的操作日志中, 即 [oplog](https://docs.mongodb.com/manual/core/replica-set-oplog/). 有关主节点操作的更多信息, 请参见 [Replica Set Primary](https://docs.mongodb.com/manual/core/replica-set-primary/). 25 | 26 | ![](https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg "Diagram of default routing of reads and writes to the primary.") 27 | 28 | 从节点复制主节点的 oplog 然后根据该操作复现,使得从节点的数据集映射了主节点数据集。如果主节点不可用,合格的从节点将会进行选举推选自己成为新的主节点。有关从节点的更多信息,请参见 [Replica Set Secondary Members](https://docs.mongodb.com/manual/core/replica-set-secondary/). 29 | 30 | ![](https://docs.mongodb.com/manual/_images/replica-set-primary-with-two-secondaries.bakedsvg.svg "Diagram of a 3 member replica set that consists of a primary and two secondaries.") 31 | 32 | 您可以将一个额外的 [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod) 实例作为仲裁节点添加到副本集。仲裁节点不维护数据集。仲裁节点的目的是通过响应其他节点的心跳和选举请求来维持副本集中的额定成员。因为它们不存储数据,所以仲裁节点可以成为提供副本集仲裁功能的好方法,其开销比具有数据集完全功能的成员节点要低。如果您的副本集有偶数个节点,请添加一个仲裁节点来确保选举能获得大多数支持的结果。仲裁节点不需要专门的机器。有关仲裁节点的更多信息,请参阅 [Replica Set Arbiter](https://docs.mongodb.com/manual/core/replica-set-arbiter/). 33 | 34 | ![](https://docs.mongodb.com/manual/_images/replica-set-primary-with-secondary-and-arbiter.bakedsvg.svg "Diagram of a replica set that consists of a primary, a secondary, and an arbiter.") 35 | 36 | 一个[仲裁节点](https://docs.mongodb.com/manual/core/replica-set-arbiter/)将永远是[仲裁节点](https://docs.mongodb.com/manual/core/replica-set-arbiter/), 而选举中[主节点](https://docs.mongodb.com/manual/core/replica-set-primary/)可降级并成为一个[从节点](https://docs.mongodb.com/manual/core/replica-set-secondary/), [从节点](https://docs.mongodb.com/manual/core/replica-set-secondary/)也可以成为[主节点](https://docs.mongodb.com/manual/core/replica-set-primary/)。 37 | 38 | ## 异步复制 39 | 40 | 从节点是异步的同步来自主节点的操作。通过复现主节点的操作之后,即使一个或多个节点挂了,复制集也可以继续工作。有关复制机制的更多信息,请参见[副本集 Oplog](https://docs.mongodb.com/manual/core/replica-set-oplog/#replica-set-oplog) 和 [副本集数据同步](https://docs.mongodb.com/manual/core/replica-set-sync/#replica-set-sync)。 41 | 42 | ## 自动熔断 43 | 44 | 当主节点超过 10 秒钟的时间不与其他成员沟通时,合格的从节点将举行选举,推举自己成为新的主节点。选举中获得大多数选票的从节点将晋升为主节点。 45 | 46 | 3.2 版本更新: MongoDB 引入了第 1 版本复制协议 \([`protocolVersion:1`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.protocolVersion)\) 来减少副本集的熔断时间并且加快检查出多个主节点并行情况的时间. 新的副本集会默认使用 [`protocolVersion:1`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.protocolVersion). 之前的 MongoDB 版本使用弟 0 版协议. 47 | 48 | ![](https://docs.mongodb.com/manual/_images/replica-set-trigger-election.bakedsvg.svg "Diagram of an election of a new primary. In a three member replica set with two secondaries, the primary becomes unreachable. The loss of a primary triggers an election where one of the secondaries becomes the new primary") 49 | 50 | 尽管时间可能不同,但故熔断过程通常会在一分钟内完成。例如,副本集的成员可能需要 10-30 秒才能确认[主节点](https://docs.mongodb.com/manual/reference/glossary/#term-primary) 不可用 \(详见 [`electionTimeoutMillis`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.settings.electionTimeoutMillis)\)。剩下的某个从节点[选举](https://docs.mongodb.com/manual/reference/glossary/#term-election)成为新的主节点。选举过程可能需要 10-30 秒。 51 | 52 | 3.2 版本更新: 从 MongoDB 3.2 开始, 通过[副本选举加强版](https://docs.mongodb.com/manual/release-notes/3.2/#rel-notes-rs-enhancements), MongoDB 降低了副本集熔断时间. 查看 [replication election enhancements](https://docs.mongodb.com/manual/release-notes/3.2/#rel-notes-rs-enhancements) 获取更多信息. 53 | 54 | 更多信息参见 [副本集选举](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections) 和 [Rollbacks During Replica Set Failover](https://docs.mongodb.com/manual/core/replica-set-rollbacks/#replica-set-rollbacks). 55 | 56 | ## 读操作 57 | 58 | 默认情况下, 客户端从主节点 [\[1\]](#edge-cases-2-primaries) 读取数据; 然而, 客户端可用通过 [read preference](https://docs.mongodb.com/manual/core/read-preference/) 来指定对从节点进行读操作. 不过由于[异步复制](#asynchronous-replication) 的原因从节点读取数据存在延迟的情况 \(数据尚未同步到从节点\). 更多信息可以参见 [Read Preference](https://docs.mongodb.com/manual/core/read-preference/). 59 | 60 | In MongoDB, clients can see the results of writes before the writes are [durable](https://docs.mongodb.com/manual/reference/glossary/#term-durable): 61 | 62 | * Regardless of [write concern](https://docs.mongodb.com/manual/reference/write-concern/) , other clients using \[`"local"`\]\([https://docs.mongodb.com/manual/reference/read-concern/\#readconcern."local](https://docs.mongodb.com/manual/reference/read-concern/#readconcern."local)"\) \(i.e. the default\) readConcern can see the result of a write operation before the write operation is acknowledged to the issuing client. 63 | * Clients using \[`"local"`\]\([https://docs.mongodb.com/manual/reference/read-concern/\#readconcern."local](https://docs.mongodb.com/manual/reference/read-concern/#readconcern."local)"\) \(i.e. the default\) readConcern can read data which may be subsequently [rolled back](https://docs.mongodb.com/manual/core/replica-set-rollbacks/) . 64 | 65 | For more information on read isolations, consistency and recency for MongoDB, see [Read Isolation, Consistency, and Recency](https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/). 66 | 67 | ## 附加特性 68 | 69 | 副本集提供了许多选项来满足应用的需求. 例如, 你可以通过[多个数据中心的节点](https://docs.mongodb.com/manual/core/replica-set-architecture-geographically-distributed/)来部署副本集, 或者调整一些节点的 [`members[n].priority`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.members[n].priority) 来控制选举结果. 副本集同时还支持设置专门的节点进行报告, 灾难恢复, 或者备份等功能. 70 | 71 | 更多信息参见 [Priority 0 副本集节点](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#replica-set-secondary-only-members), [隐藏副本集节点](https://docs.mongodb.com/manual/core/replica-set-hidden-member/#replica-set-hidden-members)和[延迟副本集节点](https://docs.mongodb.com/manual/core/replica-set-delayed-member/#replica-set-delayed-members). 72 | 73 | \[1\] _\(_[_1_](https://docs.mongodb.com/manual/replication/#id1)_,_[_2_](https://docs.mongodb.com/manual/replication/#id3)_\) _In [some circumstances](https://docs.mongodb.com/manual/reference/read-preference/#edge-cases), two nodes in a replica set may _transiently _believe that they are the primary, but at most, one of them will be able to complete writes with [`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority") write concern. The node that can complete [`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority") writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a [network partition](https://docs.mongodb.com/manual/reference/glossary/#term-network-partition). When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference[`primary`](https://docs.mongodb.com/manual/reference/read-preference/#primary), and new writes to the former primary will eventually roll back. 74 | 75 | -------------------------------------------------------------------------------- /replication/member/README.md: -------------------------------------------------------------------------------- 1 | # Replica Set Members 2 | 3 | MongoDB 的 _复制集_ 是一组 [`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)进程实例, 提供了冗余和高可用性. 复制集的成员是: 4 | 5 | [主节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-primary-member). 6 | 7 |      主节点接受所有的写操作. 8 | 9 | [从节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members). 10 | 11 |      从节点复现主节点的操作维护与其相同的数据集. 从节点可以配置用户一些特别的用途. 例如, 从节点可以是 [不投票的](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-non-voting-members) 或者 [priority 0](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#replica-set-secondary-only-members). 12 | 13 | 你也可以在副本集中维护一个 [仲裁节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-arbiters). 仲裁节点不复制数据. 但是, 当前主节点不可用时, 可以参与新的主节点的选举. 14 | 15 | 最小的副本集推荐形式为三个数据承载节点: 一个 [主节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-primary-member)与两个 [从节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members). 你也可以替换为 _2_ 个数据承载节点: 一个 [主](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-primary-member), 一个 [从](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members), 和一个 [仲裁](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-arbiters)节点, 但是至少有三个数据承载节点可以提供更好的冗余. 16 | 17 | 3.0.0 版本更新: 一个副本集可以最多 [50 个节点](https://docs.mongodb.com/manual/release-notes/3.0/#replica-sets-max-members) 但是至多 7 节点投票.[\[1\]](https://docs.mongodb.com/manual/core/replica-set-members/#master-slave) 之前的版本里, 副本集最多能有 12 个节点. 18 | 19 | ## 主节点 20 | 21 | 主节点是副本集中唯一接受写操作的节点. MongoDB 在主节点上应用写操作然后记录操作到 [oplog](https://docs.mongodb.com/manual/core/replica-set-oplog/). [从节点](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members) 复制这个 log 并且复现这些操作来同步数据. 22 | 23 | 下例中三个成员的副本集, 主节点接受所有的写操作. 从节点通过 oplog 来同步数据. 24 | 25 | ![](https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg "Diagram of default routing of reads and writes to the primary.") 26 | 27 | 副本集中的所有节点都可以接受读操作. 不过, 默认情况下, 应用会直接从主节点来读取数据. 参见 [Read Preference](https://docs.mongodb.com/manual/core/read-preference/) 获取更多修改默认读行为的信息. 28 | 29 | 一个副本集最多有一个主节点.[\[2\]](https://docs.mongodb.com/manual/core/replica-set-members/#edge-cases-2-primaries) 如果当前主节点不可用, 通过选举来确认新的主节点. 更多信息参见 [Replica Set Elections](https://docs.mongodb.com/manual/core/replica-set-elections/). 30 | 31 | ## 从节点 32 | 33 | 一个从节点维持了[主节点](https://docs.mongodb.com/manual/reference/glossary/#term-primary)的数据集副本. 拷贝过程, 是从节点通过主节点的 [oplog](https://docs.mongodb.com/manual/core/replica-set-oplog/) 来复现操作实现的一个异步过程. 一个副本集可以有一个或者多个从节点. 34 | 35 | 下图中三个节点的副本集有两个从节点. 从节点通过主节点的 oplog 来同步数据. 36 | 37 | ![](https://docs.mongodb.com/manual/_images/replica-set-primary-with-two-secondaries.bakedsvg.svg "Diagram of a 3 member replica set that consists of a primary and two secondaries.") 38 | 39 | 尽管客户端不能通过从节点来写入数据, 但是可以进行读操作. 参见 [Read Preference](https://docs.mongodb.com/manual/core/read-preference/) 获取更多客户端如何从从库读取数据的信息. 40 | 41 | 一个从节点可以变成主节点. 如果当前主节点不可用, 副本集则会举行一场[选举](https://docs.mongodb.com/manual/reference/glossary/#term-election)来选择选择一个从库成为新的主节点 (参见 [Replica Set Elections](https://docs.mongodb.com/manual/core/replica-set-elections/). 42 | 43 | 你可以配置从节点用于特别的目的, 比如: 44 | 45 | * Prevent it from becoming a primary in an election, which allows it to reside in a secondary data center or to serve as a cold standby. 参见 [Priority 0 节点](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/). 46 | * Prevent applications from reading from it, which allows it to run applications that require separation from normal traffic. 参见 [Hidden 节点](https://docs.mongodb.com/manual/core/replica-set-hidden-member/). 47 | * Keep a running “historical” snapshot for use in recovery from certain errors, such as unintentionally deleted databases. 参见 [Delayed 节点](https://docs.mongodb.com/manual/core/replica-set-delayed-member/). 48 | 49 | ## 仲裁节点 50 | 51 | 仲裁节点 **不存储** 数据, 也 **不能** 成为主节点. 副本集可以通过仲裁节点来[头片](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections). 仲裁节点 _永远_ 有一个 `1` 选举票, 从而使得副本集可以拥有基数张票, 可以避免引入新的节点来投票的开销. 52 | 53 | 54 | >
IMPORTANT
55 | > 不要在主节点或者从节点的系统上运行仲裁节点.
56 | >
57 | 58 | 59 | 要添加仲裁节点, 参见 [Add an arbiter to Replica Set](https://docs.mongodb.com/manual/tutorial/add-replica-set-arbiter/). 60 | 61 | >
WARNING
62 | > 通常来说, 避免在每个副本集中部署超过一个仲裁节点.
63 | >
64 | 65 | 对于以下 MongoDB 版本, 相比 `pv0` 中有仲裁节点的副本集而言 `pv1` 增加了 [`w:1`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern.) 回滚的可能性: 66 | 67 | * MongoDB 3.4.1 68 | * MongoDB 3.4.0 69 | * MongoDB 3.2.11 or earlier 70 | 71 | 更多参见 [Replica Set Protocol Versions](https://docs.mongodb.com/manual/reference/replica-set-protocol-versions/). 72 | 73 | | [\[1\]](https://docs.mongodb.com/manual/core/replica-set-members/#id1) | While replica sets are the recommended solution for production, a replica set can support up to [`50members`](https://docs.mongodb.com/manual/reference/limits/#Number-of-Members-of-a-Replica-Set)in total. If your deployment requires more than 50 members, you’ll need to use [master-slave](https://docs.mongodb.com/manual/core/master-slave/)replication. However, master-slave replication lacks the automatic failover capabilities. | 74 | | :--- | :--- | 75 | 76 | 77 | | [\[2\]](https://docs.mongodb.com/manual/core/replica-set-members/#id2) | In [some circumstances](https://docs.mongodb.com/manual/reference/read-preference/#edge-cases), two nodes in a replica set may_transiently_believe that they are the primary, but at most, one of them will be able to complete writes with [`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority")write concern. The node that can complete [`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority")writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a [network partition](https://docs.mongodb.com/manual/reference/glossary/#term-network-partition). When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference [`primary`](https://docs.mongodb.com/manual/reference/read-preference/#primary), and new writes to the former primary will eventually roll back. | 78 | | :--- | :--- | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /replication/member/arbiter.md: -------------------------------------------------------------------------------- 1 | # Replica Set Arbiter 2 | 3 | On this page 4 | 5 | * [Example](https://docs.mongodb.com/manual/core/replica-set-arbiter/#example) 6 | * [Security](https://docs.mongodb.com/manual/core/replica-set-arbiter/#security) 7 | 8 | An arbiter does**not**have a copy of data set and**cannot**become a primary. Replica sets may have arbiters to add a vote in[elections for primary](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections). Arbiters_always_have exactly`1`election vote, and thus allow replica sets to have an uneven number of voting members without the overhead of an additional member that replicates data. 9 | 10 | IMPORTANT 11 | 12 | Do not run an arbiter on systems that also host the primary or the secondary members of the replica set. 13 | 14 | To add an arbiter, see[Add an Arbiter to Replica Set](https://docs.mongodb.com/manual/tutorial/add-replica-set-arbiter/). 15 | 16 | WARNING 17 | 18 | In general, avoid deploying more than one arbiter per replica set. 19 | 20 | For the following MongoDB versions,`pv1`increases the likelihood of[`w:1`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern.)rollbacks compared to`pv0`for replica sets with arbiters: 21 | 22 | * MongoDB 3.4.1 23 | * MongoDB 3.4.0 24 | * MongoDB 3.2.11 or earlier 25 | 26 | See[Replica Set Protocol Versions](https://docs.mongodb.com/manual/reference/replica-set-protocol-versions/). 27 | 28 | ## Example 29 | 30 | For example, in the following replica set, an arbiter allows the set to have an odd number of votes for elections: 31 | 32 | ![](https://docs.mongodb.com/manual/_images/replica-set-four-members-add-arbiter.bakedsvg.svg "Diagram of a four member replica set plus an arbiter for odd number of votes.") 33 | 34 | ## Security 35 | 36 | ### Authentication 37 | 38 | When running with[`authorization`](https://docs.mongodb.com/manual/reference/configuration-options/#security.authorization), arbiters exchange credentials with other members of the set to authenticate via`keyfiles`. MongoDB encrypts the authentication process. The MongoDB authentication exchange is cryptographically secure. 39 | 40 | Because arbiters do not store data, they do not possess the internal table of user and role mappings used for authentication. Thus, the only way to log on to an arbiter with authorization active is to use the[localhost exception](https://docs.mongodb.com/manual/core/security-users/#localhost-exception). 41 | 42 | ### Communication 43 | 44 | The only communication between arbiters and other set members are: votes during elections, heartbeats, and configuration data. These exchanges are not encrypted. 45 | 46 | **However**, if your MongoDB deployment uses TLS/SSL, MongoDB will encrypt_all_communication between replica set members. See[Configure mongod and mongos for TLS/SSL](https://docs.mongodb.com/manual/tutorial/configure-ssl/)for more information. 47 | 48 | As with all MongoDB components, run arbiters in trusted network environments. 49 | 50 | -------------------------------------------------------------------------------- /replication/member/primary.md: -------------------------------------------------------------------------------- 1 | # Replica Set Primary 2 | 3 | The primary is the only member in the replica set that receives write operations. MongoDB applies write operations on the[primary](https://docs.mongodb.com/manual/reference/glossary/#term-primary)and then records the operations on the primary’s[oplog](https://docs.mongodb.com/manual/core/replica-set-oplog/).[Secondary](https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members)members replicate this log and apply the operations to their data sets. 4 | 5 | In the following three-member replica set, the primary accepts all write operations. Then the secondaries replicate the oplog to apply to their data sets. 6 | 7 | ![](https://docs.mongodb.com/manual/_images/replica-set-read-write-operations-primary.bakedsvg.svg "Diagram of default routing of reads and writes to the primary.") 8 | 9 | All members of the replica set can accept read operations. However, by default, an application directs its read operations to the primary member. See[Read Preference](https://docs.mongodb.com/manual/core/read-preference/)for details on changing the default read behavior. 10 | 11 | The replica set can have at most one primary.[\[1\]](https://docs.mongodb.com/manual/core/replica-set-primary/#edge-cases-2-primaries)If the current primary becomes unavailable, an election determines the new primary. See[Replica Set Elections](https://docs.mongodb.com/manual/core/replica-set-elections/)for more details. 12 | 13 | In the following 3-member replica set, the primary becomes unavailable. This triggers an election which selects one of the remaining secondaries as the new primary. 14 | 15 | ![](https://docs.mongodb.com/manual/_images/replica-set-trigger-election.bakedsvg.svg "Diagram of an election of a new primary. In a three member replica set with two secondaries, the primary becomes unreachable. The loss of a primary triggers an election where one of the secondaries becomes the new primary") 16 | 17 | | [\[1\]](https://docs.mongodb.com/manual/core/replica-set-primary/#id1) | In[some circumstances](https://docs.mongodb.com/manual/reference/read-preference/#edge-cases), two nodes in a replica set may_transiently_believe that they are the primary, but at most, one of them will be able to complete writes with[`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority")write concern. The node that can complete[`{w:"majority"}`](https://docs.mongodb.com/manual/reference/write-concern/#writeconcern."majority")writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a[network partition](https://docs.mongodb.com/manual/reference/glossary/#term-network-partition). When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference[`primary`](https://docs.mongodb.com/manual/reference/read-preference/#primary), and new writes to the former primary will eventually roll back. | 18 | | :--- | :--- | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /replication/member/secondary/delayed.md: -------------------------------------------------------------------------------- 1 | # Delayed Replica Set Members 2 | 3 | On this page 4 | 5 | * [Considerations](https://docs.mongodb.com/manual/core/replica-set-delayed-member/#considerations) 6 | * [Example](https://docs.mongodb.com/manual/core/replica-set-delayed-member/#example) 7 | * [Configuration](https://docs.mongodb.com/manual/core/replica-set-delayed-member/#configuration) 8 | 9 | Delayed members contain copies of a[replica set’s](https://docs.mongodb.com/manual/reference/glossary/#term-replica-set)data set. However, a delayed member’s data set reflects an earlier, or delayed, state of the set. For example, if the current time is 09:52 and a member has a delay of an hour, the delayed member has no operation more recent than 08:52. 10 | 11 | Because delayed members are a “rolling backup” or a running “historical” snapshot of the data set, they may help you recover from various kinds of human error. For example, a delayed member can make it possible to recover from unsuccessful application upgrades and operator errors including dropped databases and collections. 12 | 13 | ## Considerations 14 | 15 | ### Requirements 16 | 17 | Delayed members: 18 | 19 | * **Must be** 20 | [priority 0](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#replica-set-secondary-only-members) 21 | members. Set the priority to 0 to prevent a delayed member from becoming primary. 22 | * **Should be** 23 | [hidden](https://docs.mongodb.com/manual/core/replica-set-hidden-member/#replica-set-hidden-members) 24 | members. Always prevent applications from seeing and querying delayed members. 25 | * _do_ 26 | vote in 27 | [elections](https://docs.mongodb.com/manual/reference/glossary/#term-election) 28 | for primary, if 29 | [`members[n].votes`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.members[n].votes) 30 | is set to 1. 31 | 32 | ### Behavior 33 | 34 | Delayed members copy and apply operations from the source[oplog](https://docs.mongodb.com/manual/reference/glossary/#term-oplog)on a delay. When choosing the amount of delay, consider that the amount of delay: 35 | 36 | * must be equal to or greater than your expected maintenance window durations. 37 | * must be 38 | _smaller_ 39 | than the capacity of the oplog. For more information on oplog size, see 40 | [Oplog Size](https://docs.mongodb.com/manual/core/replica-set-oplog/#replica-set-oplog-sizing) 41 | . 42 | 43 | ### Sharding 44 | 45 | In sharded clusters, delayed members have limited utility when the[balancer](https://docs.mongodb.com/manual/reference/glossary/#term-balancer)is enabled. Because delayed members replicate chunk migrations with a delay, the state of delayed members in a sharded cluster are not useful for recovering to a previous state of the sharded cluster if any migrations occur during the delay window. 46 | 47 | ## Example 48 | 49 | In the following 5-member replica set, the primary and all secondaries have copies of the data set. One member applies operations with a delay of 3600 seconds \(one hour\). This delayed member is also_hidden_and is a_priority 0 member_. 50 | 51 | ![](https://docs.mongodb.com/manual/_images/replica-set-delayed-member.bakedsvg.svg "Diagram of a 5 member replica set with a hidden delayed priority 0 member.") 52 | 53 | ## Configuration 54 | 55 | A delayed member has its[`members[n].priority`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.members[n].priority)equal to`0`,[`members[n].hidden`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.members[n].hidden)equal to`true`, and its[`members[n].slaveDelay`](https://docs.mongodb.com/manual/reference/replica-configuration/#rsconf.members[n].slaveDelay)equal to the number of seconds of delay: 56 | 57 | ```js 58 | { 59 | "_id" : , 60 | "host" : , 61 | "priority" : 0, 62 | "slaveDelay" : , 63 | "hidden" : true 64 | } 65 | ``` 66 | 67 | To configure a delayed member, see[Configure a Delayed Replica Set Member](https://docs.mongodb.com/manual/tutorial/configure-a-delayed-replica-set-member/). 68 | 69 | -------------------------------------------------------------------------------- /replication/member/secondary/hidden.md: -------------------------------------------------------------------------------- 1 | # Hidden Replica Set Members 2 | 3 | On this page 4 | 5 | * [Behavior](https://docs.mongodb.com/manual/core/replica-set-hidden-member/#behavior) 6 | * [Further Reading](https://docs.mongodb.com/manual/core/replica-set-hidden-member/#further-reading) 7 | 8 | A hidden member maintains a copy of the[primary’s](https://docs.mongodb.com/manual/reference/glossary/#term-primary)data set but is**invisible**to client applications. Hidden members are good for workloads with different usage patterns from the other members in the[replica set](https://docs.mongodb.com/manual/reference/glossary/#term-replica-set). Hidden members must always be[priority 0 members](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#replica-set-secondary-only-members)and so**cannot become primary**. The[`db.isMaster()`](https://docs.mongodb.com/manual/reference/method/db.isMaster/#db.isMaster)method does not display hidden members. Hidden members, however,**may vote**in[elections](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections). 9 | 10 | In the following five-member replica set, all four secondary members have copies of the primary’s data set, but one of the secondary members is hidden. 11 | 12 | ![](https://docs.mongodb.com/manual/_images/replica-set-hidden-member.bakedsvg.svg "Diagram of a 5 member replica set with a hidden priority 0 member.") 13 | 14 | ## Behavior 15 | 16 | ### Read Operations 17 | 18 | Clients will not distribute reads with the appropriate[read preference](https://docs.mongodb.com/manual/core/read-preference/)to hidden members. As a result, these members receive no traffic other than basic replication. Use hidden members for dedicated tasks such as reporting and backups.[Delayed members](https://docs.mongodb.com/manual/core/replica-set-delayed-member/)should be hidden. 19 | 20 | In a sharded cluster,[`mongos`](https://docs.mongodb.com/manual/reference/program/mongos/#bin.mongos)do not interact with hidden members. 21 | 22 | ### Voting 23 | 24 | Hidden members_may_vote in replica set elections. If you stop a voting hidden member, ensure that the set has an active majority or the[primary](https://docs.mongodb.com/manual/reference/glossary/#term-primary)will step down. 25 | 26 | For the purposes of backups, 27 | 28 | * If using the MMAPv1 storage engine, you can avoid stopping a hidden member with the[`db.fsyncLock()`](https://docs.mongodb.com/manual/reference/method/db.fsyncLock/#db.fsyncLock)and[`db.fsyncUnlock()`](https://docs.mongodb.com/manual/reference/method/db.fsyncUnlock/#db.fsyncUnlock)operations to flush all writes and lock the[`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)instance for the duration of the backup operation. 29 | 30 | * Changed in version 3.2:[`db.fsyncLock()`](https://docs.mongodb.com/manual/reference/method/db.fsyncLock/#db.fsyncLock)can ensure that the data files do not change for MongoDB instances using either the MMAPv1 or the WiredTiger storage engines, thus providing consistency for the purposes of creating backups. 31 | 32 | In previous MongoDB versions,[`db.fsyncLock()`](https://docs.mongodb.com/manual/reference/method/db.fsyncLock/#db.fsyncLock)_cannot_guarantee a consistent set of files for low-level backups \(e.g. via file copy`cp`,`scp`,`tar`\) for WiredTiger. 33 | 34 | ## Further Reading 35 | 36 | For more information about backing up MongoDB databases, see[MongoDB Backup Methods](https://docs.mongodb.com/manual/core/backups/). To configure a hidden member, see[Configure a Hidden Replica Set Member](https://docs.mongodb.com/manual/tutorial/configure-a-hidden-replica-set-member/). 37 | 38 | -------------------------------------------------------------------------------- /replication/member/secondary/priority.md: -------------------------------------------------------------------------------- 1 | # Priority 0 Replica Set Members 2 | 3 | On this page 4 | 5 | * [Priority 0 Members as Standbys](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#priority-0-members-as-standbys) 6 | * [Priority 0 Members and Failover](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#priority-0-members-and-failover) 7 | * [Configuration](https://docs.mongodb.com/manual/core/replica-set-priority-0-member/#configuration) 8 | 9 | A_priority 0_member is a secondary that**cannot**become[primary](https://docs.mongodb.com/manual/reference/glossary/#term-primary)._Priority 0_members cannot_trigger_[elections](https://docs.mongodb.com/manual/reference/glossary/#term-election). Otherwise these members function as normal secondaries. A_priority 0_member maintains a copy of the data set, accepts read operations, and votes in elections. Configure a_priority 0_member to prevent[secondaries](https://docs.mongodb.com/manual/reference/glossary/#term-secondary)from becoming primary, which is particularly useful in multi-data center deployments. 10 | 11 | For example, in the following diagram, one data center hosts the primary and a secondary. A second data center hosts one_priority 0_member that cannot become primary. 12 | 13 | ![](https://docs.mongodb.com/manual/_images/replica-set-three-members-geographically-distributed.bakedsvg.svg "Diagram of a 3 member replica set distributed across two data centers. Replica set includes a priority 0 member.") 14 | 15 | ## Priority 0 Members as Standbys 16 | 17 | A_priority 0_member can function as a standby. In some replica sets, it might not be possible to add a new member in a reasonable amount of time. A standby member keeps a current copy of the data to be able to replace an unavailable member. 18 | 19 | In many cases, you need not set standby to_priority 0_. However, in sets with varied hardware or[geographic distribution](https://docs.mongodb.com/manual/core/replica-set-architecture-geographically-distributed/#replica-set-geographical-distribution), a_priority 0_standby ensures that only qualified members become primary. 20 | 21 | A_priority 0_standby may also be valuable for some members of a set with different hardware or workload profiles. In these cases, deploy a member with_priority 0_so it can’t become primary. Also consider using an[hidden member](https://docs.mongodb.com/manual/core/replica-set-hidden-member/#replica-set-hidden-members)for this purpose. 22 | 23 | If your set already has seven voting members, also configure the member as[non-voting](https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-non-voting-members). 24 | 25 | ## Priority 0 Members and Failover 26 | 27 | When configuring a_priority 0_member, consider potential failover patterns, including all possible network partitions. Always ensure that your main data center contains both a quorum of voting members and contains members that are eligible to be primary. 28 | 29 | ## Configuration 30 | 31 | To configure a_priority 0_member, see[Prevent Secondary from Becoming Primary](https://docs.mongodb.com/manual/tutorial/configure-secondary-only-replica-set-member/). 32 | 33 | -------------------------------------------------------------------------------- /replication/op-log.md: -------------------------------------------------------------------------------- 1 | # Replica Set Oplog 2 | 3 | On this page 4 | 5 | * [Oplog Size](https://docs.mongodb.com/manual/core/replica-set-oplog/#oplog-size) 6 | * [Workloads that Might Require a Larger Oplog Size](https://docs.mongodb.com/manual/core/replica-set-oplog/#workloads-that-might-require-a-larger-oplog-size) 7 | * [Oplog Status](https://docs.mongodb.com/manual/core/replica-set-oplog/#oplog-status) 8 | 9 | The[oplog](https://docs.mongodb.com/manual/reference/glossary/#term-oplog)\(operations log\) is a special[capped collection](https://docs.mongodb.com/manual/reference/glossary/#term-capped-collection)that keeps a rolling record of all operations that modify the data stored in your databases. MongoDB applies database operations on the[primary](https://docs.mongodb.com/manual/reference/glossary/#term-primary)and then records the operations on the primary’s oplog. The[secondary](https://docs.mongodb.com/manual/reference/glossary/#term-secondary)members then copy and apply these operations in an asynchronous process. All replica set members contain a copy of the oplog, in the[`local.oplog.rs`](https://docs.mongodb.com/manual/reference/local-database/#local.oplog.rs)collection, which allows them to maintain the current state of the database. 10 | 11 | To facilitate replication, all replica set members send heartbeats \(pings\) to all other members. Any member can import oplog entries from any other member. 12 | 13 | Each operation in the oplog is[idempotent](https://docs.mongodb.com/manual/reference/glossary/#term-idempotent). That is, oplog operations produce the same results whether applied once or multiple times to the target dataset. 14 | 15 | ## Oplog Size 16 | 17 | When you start a replica set member for the first time, MongoDB creates an oplog of a default size. 18 | 19 | For Unix and Windows systems 20 | 21 | The default oplog size depends on the storage engine: 22 | 23 | | Storage Engine | Default Oplog Size | Lower Bound | Upper Bound | 24 | | :--- | :--- | :--- | :--- | 25 | | [In-Memory Storage Engine](https://docs.mongodb.com/manual/core/inmemory/) | 5% of physical memory | 50 MB | 50 GB | 26 | | [WiredTiger Storage Engine](https://docs.mongodb.com/manual/core/wiredtiger/) | 5% of free disk space | 990 MB | 50 GB | 27 | | [MMAPv1 Storage Engine](https://docs.mongodb.com/manual/core/mmapv1/) | 5% of free disk space | 990 MB | 50 GB | 28 | 29 | For 64-bit macOS systems 30 | 31 | The default oplog size is 192 MB of either physical memory or free disk space depending on the storage engine: 32 | 33 | | Storage Engine | Default Oplog Size | 34 | | :--- | :--- | 35 | | [In-Memory Storage Engine](https://docs.mongodb.com/manual/core/inmemory/) | 192 MB of physical memory | 36 | | [WiredTiger Storage Engine](https://docs.mongodb.com/manual/core/wiredtiger/) | 192 MB of free disk space | 37 | | [MMAPv1 Storage Engine](https://docs.mongodb.com/manual/core/mmapv1/) | 192 MB of free disk space | 38 | 39 | In most cases, the default oplog size is sufficient. For example, if an oplog is 5% of free disk space and fills up in 24 hours of operations, then secondaries can stop copying entries from the oplog for up to 24 hours without becoming too stale to continue replicating. However, most replica sets have much lower operation volumes, and their oplogs can hold much higher numbers of operations. 40 | 41 | Before[`mongod`](https://docs.mongodb.com/manual/reference/program/mongod/#bin.mongod)creates an oplog, you can specify its size with the[`oplogSizeMB`](https://docs.mongodb.com/manual/reference/configuration-options/#replication.oplogSizeMB)option. However, after you have started a replica set member for the first time, you can only change the size of the oplog using the[Change the Size of the Oplog](https://docs.mongodb.com/manual/tutorial/change-oplog-size/)procedure. 42 | 43 | ## Workloads that Might Require a Larger Oplog Size 44 | 45 | If you can predict your replica set’s workload to resemble one of the following patterns, then you might want to create an oplog that is larger than the default. Conversely, if your application predominantly performs reads with a minimal amount of write operations, a smaller oplog may be sufficient. 46 | 47 | The following workloads might require a larger oplog size. 48 | 49 | ### Updates to Multiple Documents at Once 50 | 51 | The oplog must translate multi-updates into individual operations in order to maintain[idempotency](https://docs.mongodb.com/manual/reference/glossary/#term-idempotent). This can use a great deal of oplog space without a corresponding increase in data size or disk use. 52 | 53 | ### Deletions Equal the Same Amount of Data as Inserts 54 | 55 | If you delete roughly the same amount of data as you insert, the database will not grow significantly in disk use, but the size of the operation log can be quite large. 56 | 57 | ### Significant Number of In-Place Updates 58 | 59 | If a significant portion of the workload is updates that do not increase the size of the documents, the database records a large number of operations but does not change the quantity of data on disk. 60 | 61 | ## Oplog Status 62 | 63 | To view oplog status, including the size and the time range of operations, issue the[`rs.printReplicationInfo()`](https://docs.mongodb.com/manual/reference/method/rs.printReplicationInfo/#rs.printReplicationInfo)method. For more information on oplog status, see[Check the Size of the Oplog](https://docs.mongodb.com/manual/tutorial/troubleshoot-replica-sets/#replica-set-troubleshooting-check-oplog-size). 64 | 65 | Under various exceptional situations, updates to a[secondary’s](https://docs.mongodb.com/manual/reference/glossary/#term-secondary)oplog might lag behind the desired performance time. Use[`db.getReplicationInfo()`](https://docs.mongodb.com/manual/reference/method/db.getReplicationInfo/#db.getReplicationInfo)from a secondary member and the[replication status](https://docs.mongodb.com/manual/reference/method/db.getReplicationInfo/)output to assess the current state of replication and determine if there is any unintended replication delay. 66 | 67 | See[Replication Lag](https://docs.mongodb.com/manual/tutorial/troubleshoot-replica-sets/#replica-set-replication-lag)for more information. 68 | 69 | -------------------------------------------------------------------------------- /security/README.md: -------------------------------------------------------------------------------- 1 | # Security 2 | 3 | MongoDB provides various features, such as authentication, access control, encryption, to secure your MongoDB deployments. Some key security features include: 4 | 5 | | Authentication | Authorization | TLS/SSL | Enterprise Only | 6 | | :--- | :--- | :--- | :--- | 7 | | [Authentication](https://docs.mongodb.com/manual/core/authentication/)[SCRAM-SHA-1](https://docs.mongodb.com/manual/core/security-scram-sha-1/)[x.509](https://docs.mongodb.com/manual/core/security-x.509/) | [Role-Based Access Control](https://docs.mongodb.com/manual/core/authorization/)[Enable Auth](https://docs.mongodb.com/manual/tutorial/enable-authentication/)[Manage Users and Roles](https://docs.mongodb.com/manual/tutorial/manage-users-and-roles/) | [Transport Encryption](https://docs.mongodb.com/manual/core/security-transport-encryption/)[Configure mongod and mongos for TLS/SSL](https://docs.mongodb.com/manual/tutorial/configure-ssl/)[TLS/SSL Configuration for Clients](https://docs.mongodb.com/manual/tutorial/configure-ssl-clients/) | [Kerberos Authentication](https://docs.mongodb.com/manual/core/kerberos/)[LDAP Proxy Authentication](https://docs.mongodb.com/manual/core/security-ldap/)[Encryption at Rest](https://docs.mongodb.com/manual/core/security-encryption-at-rest/)[Auditing](https://docs.mongodb.com/manual/core/auditing/) | 8 | 9 | ## Security Checklist 10 | 11 | MongoDB also provides the[Security Checklist](https://docs.mongodb.com/manual/administration/security-checklist/)for a list of recommended actions to protect a MongoDB deployment. 12 | 13 | ## Additional Resources 14 | 15 | * [Making HIPAA Compliant MongoDB Applications](https://www.mongodb.com/blog/post/making-hipaa-compliant-applications-mongodb?jmp=docs) 16 | * [Security Architecture White Paper](https://www.mongodb.com/lp/white-paper/mongodb-security-architecture?jmp=docs) 17 | * [Webinar: Securing Your MongoDB Deployment](http://www.mongodb.com/presentations/webinar-securing-your-mongodb-deployment?jmp=docs) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sharding/keys.md: -------------------------------------------------------------------------------- 1 | # Shard Keys 2 | 3 | On this page 4 | 5 | * [Shard Key Specification](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-specification) 6 | * [Shard Key Indexes](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-indexes) 7 | * [Choosing a Shard Key](https://docs.mongodb.com/manual/core/sharding-shard-key/#choosing-a-shard-key) 8 | 9 | The shard key determines the distribution of the collection’s[documents](https://docs.mongodb.com/manual/reference/glossary/#term-document)among the cluster’s[shards](https://docs.mongodb.com/manual/reference/glossary/#term-shard). The shard key is either an indexed[field](https://docs.mongodb.com/manual/reference/glossary/#term-field)or indexed[compound](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)fields that exists in every document in the collection. 10 | 11 | MongoDB[partitions](https://docs.mongodb.com/manual/reference/glossary/#term-data-partition)data in the collection using ranges of shard key values. Each range defines a non-overlapping range of shard key values and is associated with a[chunk](https://docs.mongodb.com/manual/reference/glossary/#term-chunk). 12 | 13 | MongoDB attempts to distribute chunks evenly among the shards in the cluster. The shard key has a direct relationship to the effectiveness of chunk distribution. See[Choosing a Shard Key](https://docs.mongodb.com/manual/core/sharding-shard-key/#sharding-shard-key-selection). 14 | 15 | ![](https://docs.mongodb.com/manual/_images/sharding-range-based.bakedsvg.svg "Diagram of the shard key value space segmented into smaller ranges or chunks.") 16 | 17 | IMPORTANT 18 | 19 | Once you shard a collection, the shard key and the shard key values are immutable; i.e. 20 | 21 | * You cannot select a different shard key for that collection. 22 | * You cannot update the values of the shard key fields. 23 | 24 | ## Shard Key Specification 25 | 26 | To shard a collection, you must specify the target collection and the shard key to the[`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection)method: 27 | 28 | ``` 29 | sh 30 | . 31 | shardCollection 32 | ( 33 | namespace 34 | , 35 | key 36 | ) 37 | ``` 38 | 39 | * The 40 | `namespace` 41 | parameter consists of a string 42 | `<` 43 | `database` 44 | `>` 45 | `.` 46 | `<` 47 | `collection` 48 | `>` 49 | specifying the full 50 | [namespace](https://docs.mongodb.com/manual/reference/glossary/#term-namespace) 51 | of the target collection. 52 | * The 53 | `key` 54 | parameter consists of a document containing a field and the index traversal direction for that field. 55 | 56 | For instructions specific to sharding a collection using the[hashed sharding](https://docs.mongodb.com/manual/core/hashed-sharding/#sharding-hashed)strategy, see[Shard a Collection using Hashed Sharding](https://docs.mongodb.com/manual/tutorial/deploy-sharded-cluster-hashed-sharding/#deploy-hashed-sharded-cluster-shard-collection) 57 | 58 | For instructions specific to sharding a collection using the[ranged sharding](https://docs.mongodb.com/manual/core/ranged-sharding/#sharding-ranged)strategy, see[Shard a Collection using Ranged Sharding](https://docs.mongodb.com/manual/tutorial/deploy-sharded-cluster-ranged-sharding/#deploy-ranged-sharded-cluster-shard-collection). 59 | 60 | ## Shard Key Indexes 61 | 62 | All sharded collections**must**have an index that supports the[shard key](https://docs.mongodb.com/manual/reference/glossary/#term-shard-key); i.e. the index can be an index on the shard key or a[compound index](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)where the shard key is a[prefix](https://docs.mongodb.com/manual/core/index-compound/#compound-index-prefix)of the index. 63 | 64 | * If the collection is empty, 65 | [`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection) 66 | creates the index on the shard key if such an index does not already exists. 67 | * If the collection is not empty, you must create the index first before using 68 | [`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection) 69 | . 70 | 71 | If you drop the last valid index for the shard key, recover by recreating an index on just the shard key. 72 | 73 | ### Unique Indexes 74 | 75 | For a sharded collection, only the`_id`field index and the index on the shard key or a[compound index](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)where the shard key is a[prefix](https://docs.mongodb.com/manual/core/index-compound/#compound-index-prefix)can be[unique](https://docs.mongodb.com/manual/core/index-unique/): 76 | 77 | * You cannot shard a collection that has unique indexes on other fields. 78 | * You cannot create unique indexes on other fields for a sharded collection. 79 | 80 | Through the use of the unique index on the shard key, MongoDB_can_enforce uniqueness on the shard key values. MongoDB enforces uniqueness on the_entire_key combination, and not individual components of the shard key. To enforce uniqueness on the shard key values, pass the`unique`parameter as`true`to the[`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection)method: 81 | 82 | * If the collection is empty, 83 | [`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection) 84 | creates the unique index on the shard key if such an index does not already exists. 85 | * If the collection is not empty, you must create the index first before using 86 | [`sh.shardCollection()`](https://docs.mongodb.com/manual/reference/method/sh.shardCollection/#sh.shardCollection) 87 | . 88 | 89 | Although you can have a unique[compound index](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)where the shard key is a[prefix](https://docs.mongodb.com/manual/core/index-compound/#compound-index-prefix), if using`unique`parameter, the collection must have a unique index that is on the shard key. 90 | 91 | You cannot specify a unique constraint on a[hashed index](https://docs.mongodb.com/manual/core/index-hashed/#index-type-hashed). 92 | 93 | ## Choosing a Shard Key 94 | 95 | The choice of shard key affects how the[sharded cluster](https://docs.mongodb.com/manual/reference/glossary/#term-sharded-cluster)[balancer](https://docs.mongodb.com/manual/reference/glossary/#term-balancer)creates and distributes[chunks](https://docs.mongodb.com/manual/reference/glossary/#term-chunk)across the available[shards](https://docs.mongodb.com/manual/reference/glossary/#term-shard). This affects the overall efficiency and performance of operations within the sharded cluster. 96 | 97 | The shard key affects the performance and efficiency of the[sharding strategy](https://docs.mongodb.com/manual/sharding/#sharding-strategy)used by the sharded cluster. 98 | 99 | The ideal shard key allows MongoDB to distribute documents evenly throughout the cluster. 100 | 101 | ![](https://docs.mongodb.com/manual/_images/sharded-cluster-ranged-distribution-good.bakedsvg.svg "Diagram of good shard key distribution") 102 | 103 | At minimum, consider the consequences of the[cardinality](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-range),[frequency](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-frequency), and rate of[change](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-monotonic)of a potential shard key. 104 | 105 | ### Restrictions 106 | 107 | For restrictions on shard key, see[Shard Key Limitations](https://docs.mongodb.com/manual/reference/limits/#limits-shard-keys). 108 | 109 | ### Collection Size 110 | 111 | When sharding a collection that is not empty, the shard key can constrain the maximum supported collection size for the initial sharding operation only. See`ShardingExistingCollectionDataSize`. 112 | 113 | IMPORTANT 114 | 115 | A sharded collection can grow to any size after successful sharding. 116 | 117 | ### Shard Key Cardinality 118 | 119 | The[cardinality](https://docs.mongodb.com/manual/reference/glossary/#term-cardinality)of a shard key determines the maximum number of chunks the balancer can create. This can reduce or remove the effectiveness of horizontal scaling in the cluster. 120 | 121 | A unique shard key value can exist on no more than a single chunk at any given time. If a shard key has a cardinality of`4`, then there can be no more than`4`chunks within the sharded cluster, each storing one unique shard key value. This constrains the number of effective shards in the cluster to`4`as well - adding additional shards would not provide any benefit. 122 | 123 | The following image illustrates a sharded cluster using the field`X`as the shard key. If`X`has low cardinality, the distribution of inserts may look similar to the following: 124 | 125 | ![](https://docs.mongodb.com/manual/_images/sharded-cluster-ranged-distribution-low-cardinal.bakedsvg.svg "Diagram of poor shard key distribution due to low cardinality") 126 | 127 | The cluster in this example would_not_scale horizontally, as incoming writes would only route to a subset of shards. 128 | 129 | A shard key with high cardinality does not guarantee even distribution of data across the sharded cluster, though it does better facilitate horizontal scaling. The[frequency](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-frequency)and[rate of change](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-monotonic)of the shard key also contributes to data distribution. Consider each factor when choosing a shard key. 130 | 131 | If your data model requires sharding on a key that has low cardinality, consider using a[compound index](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)using a field that has higher relative cardinality. 132 | 133 | ### Shard Key Frequency 134 | 135 | Consider a set representing the range of shard key values - the`frequency`of the shard key represents how often a given value occurs in the data. If the majority of documents contain only a subset of those values, then the chunks storing those documents become a bottleneck within the cluster. Furthermore, as those chunks grow, they may become[indivisible chunks](https://docs.mongodb.com/manual/core/sharding-data-partitioning/#jumbo-chunks)as they cannot be split any further. This reduces or removes the effectiveness of horizontal scaling within the cluster. 136 | 137 | The following image illustrates a sharded cluster using the field`X`as the shard key. If a subset of values for`X`occur with high frequency, the distribution of inserts may look similar to the following: 138 | 139 | ![](https://docs.mongodb.com/manual/_images/sharded-cluster-ranged-distribution-frequency.bakedsvg.svg "Diagram of poor shard key distribution due to high frequency") 140 | 141 | A shard key with low frequency does not guarantee even distribution of data across the sharded cluster. The[cardinality](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-cardinality)and[rate of change](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-monotonic)of the shard key also contributes to data distribution. Consider each factor when choosing a shard key. 142 | 143 | If your data model requires sharding on a key that has high frequency values, consider using a[compound index](https://docs.mongodb.com/manual/reference/glossary/#term-compound-index)using a unique or low frequency value. 144 | 145 | ### Monotonically Changing Shard Keys 146 | 147 | A shard key on a value that increases or decreases monotonically is more likely to distribute inserts to a single shard within the cluster. 148 | 149 | This occurs because every cluster has a chunk that captures a range with an upper bound of[`maxKey`](https://docs.mongodb.com/manual/reference/mongodb-extended-json/#data_maxkey).`maxKey`always compares as higher than all other values. Similarly, there is a chunk that captures a range with a lower bound of[`minKey`](https://docs.mongodb.com/manual/reference/mongodb-extended-json/#data_minkey).`minKey`always compares as lower than all other values. 150 | 151 | If the shard key value is always increasing, all new inserts are routed to the chunk with`maxKey`as the upper bound. If the shard key value is always decreasing, all new inserts are routed to the chunk with`minKey`as the lower bound. The shard containing that chunk becomes the bottleneck for write operations. 152 | 153 | The following image illustrates a sharded cluster using the field`X`as the shard key. If the values for`X`are monotonically increasing, the distribution of inserts may look similar to the following: 154 | 155 | ![](https://docs.mongodb.com/manual/_images/sharded-cluster-monotonic-distribution.bakedsvg.svg "Diagram of poor shard key distribution due to monotonically increasing or decreasing shard key") 156 | 157 | If the shard key value was monotonically decreasing, then all inserts would route to`ChunkA`instead. 158 | 159 | A shard key that does not change monotonically does not guarantee even distribution of data across the sharded cluster. The[cardinality](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-cardinality)and[frequency](https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-frequency)of the shard key also contributes to data distribution. Consider each factor when choosing a shard key. 160 | 161 | If your data model requires sharding on a key that changes monotonically, consider using[Hashed Sharding](https://docs.mongodb.com/manual/core/hashed-sharding/). 162 | 163 | -------------------------------------------------------------------------------- /sharding/zone.md: -------------------------------------------------------------------------------- 1 | - [分片](http://www.mongoing.com/docs/sharding.html) > 区域 2 | 3 | # 区域 4 | 5 | 本页内容 6 | 7 | - [行为和操作](http://www.mongoing.com/docs/core/zone-sharding.html#behavior-and-operations) 8 | - [其它资源](http://www.mongoing.com/docs/core/zone-sharding.html#additional-resource) 9 | 10 | 在分片集群中,您可以基于 [*shard key*](http://www.mongoing.com/docs/reference/glossary.html#term-shard-key) 创建分片数据的 [*zones*](http://www.mongoing.com/docs/reference/glossary.html#term-zone) 。您可以将每个区域与集群中的一个或者更多分片关联起来。一个分片可以和任意数目的非冲突区域关联。在一个均衡的集群中,MongoDB只会将一个区域包含的 [*chunks*](http://www.mongoing.com/docs/reference/glossary.html#term-chunk) 迁移到与该区域相关联的分片。 11 | 12 | 可以运用区域的一些常见开发模式如下: 13 | 14 | - 在一个特定的分片集合中分隔一个特定的数据子集。 15 | - 保证最相关的数据存储于与应用服务器地理上最相近的分片上。 16 | - 基于硬件/分片硬件的性能将数据路由到分片。 17 | 18 | 下图展示了一个拥有三个分片和两个区域的分片集群。`A` 区域表示下限为 `1` 、上限为 `10` 的范围。`B` 区域则表示下限为 `10` 、上限为 `20` 的范围。 分片 `Alpha` 和 `Beta` 有 `A` 区域。分片 `Beta` 还拥有 `B` 区域。 分片 `Charlie` 没有区域与之相关、该集群在一个稳定的状态,没有数据块违背任何区域。 19 | 20 | ![Diagram of data distribution based on zones in a sharded cluster](http://www.mongoing.com/docs/_images/sharded-cluster-zones.png) 21 | 22 | ## 行为和操作 23 | 24 | ### 范围 25 | 26 | 每个区域设计一个或多个 [*shard key*](http://www.mongoing.com/docs/reference/glossary.html#term-shard-key) 值范围。每个区域覆盖的每个范围一般包含其下界,不包含其上界。 27 | 28 | 区域不能共享范围,它们也不能有交叉的范围。 29 | 30 | ### 均衡器 31 | 32 | The [*balancer*](http://www.mongoing.com/docs/reference/glossary.html#term-balancer) attempts to evenly distribute a sharded collection’s chunks across all shards in the cluster. 33 | 34 | 对于每一个标记为要迁移的 [*chunk*](http://www.mongoing.com/docs/reference/glossary.html#term-chunk) ,均衡器检查所有配置区域内的每一个可能的目标分片。如果数据块范围属于某一个区域,那么均衡器就会将该数据块迁移到该区域上的一个分片。不属于任何区域的数据块可以存在于集群中的 *任何* 分片,并且正常迁移。 35 | 36 | 在均衡过程中,如果均衡器检测到任何违背已配置区域上给定的分片,均衡器将会把这些数据块迁移到不存在冲突的分片上。 37 | 38 | 在使用一个片键范围配置区域,并且将它与一个或多个分片关联起来之后,集群可能会花费一些时间来迁移影响的数据。这依赖于数据块的划分以及目前集群中数据的分布。当均衡完成之后,在某一给定区域的文档读取和写入将只会路由到该区域内的一个分片或几个分片。 39 | 40 | 一旦配置完成后,均衡器将在 [*balancing rounds*](http://www.mongoing.com/docs/core/sharding-balancer-administration.html#sharding-internals-balancing) 中重新检查区域。 41 | 42 | ### 片键 43 | 44 | 在定义一个区域覆盖的新范围时,您必须使用包含在 [*shard key*](http://www.mongoing.com/docs/reference/glossary.html#term-shard-key) 中的字段。如果使用一个 [*compound*](http://www.mongoing.com/docs/reference/glossary.html#term-compound-index) 片键,则该范围必须包含该片键的前缀。 45 | 46 | 例如,给定一个片键 `{ a : 1, b : 2, c : 3 }` ,创建或更新一个区域来覆盖 `b` 的值要求包括 `a` 作为前缀。创建或更新一个区域来覆盖 `c` 的值要求包括 `a` 和 `b` 作为前缀。 47 | 48 | 您不能使用片键中部包含的字段创建区域。例如,如果您先使用区域来对数据进行地理位置进行分区,片键中需要至少包括一个包含地理数据的字段。 49 | 50 | 当选择集合的片键时,考虑您可能需要用来配置区域的字段。在分片之后,您不能修改片键。查阅 [*通常,一个经过计算的片键会有一定的”随机性”,比如一个包含了其他字段加密哈希(例如 MD5或者SHA1)的片键,会使集群具有较好的写扩展性能.不过,随机的片键通常不会提供 查询隔离 的特性,而查询隔离同样是片键一个很重要的特性.*](http://www.mongoing.com/docs/core/sharding-shard-key.html#sharding-internals-choose-shard-key) 了解选择片键的考量。 51 | 52 | ### 哈希片键和区域 53 | 54 | 当在哈希片键上使用区域时,每个区域覆盖 *哈希* 片键值。给定一个片键值 `{ a : 1 }` 和区域一个下界为 `1` 上界为 `5` 的区域 `alpha` ,边界表示 `a` 的 *哈希* 值,而不是真实值。因此,并不能保证 MongoDB将 `a`值为 `1` 到 `5` 之间的文档路由到 `alpha` 区域。MongoDB将任何 *哈希* 片键值落入到 `1` 到 `5` 范围内的文档路由到区域 `alpha` 内的分片上。 55 | 56 | 一般说来,一个覆盖哈希片键值顺序范围的区域可能会出现一些预计不到的行为。 57 | 58 | 可以通过使用 `minkey` 和 `maxkey` 创建覆盖片键值整个范围的区域,以保证MongoDB将某个特定集合的所有数据控制存储在该区域的一个分片或几个分片上。 59 | 60 | ### 分片区域边界 61 | 62 | 区域范围一般包含下界,不包含上界。 63 | 64 | 参见 65 | 66 | [*Manage Shard Zones*](http://www.mongoing.com/docs/tutorial/manage-shard-zone.html) 67 | 68 | ## 其它资源 69 | 70 | - ` 白皮书: MongoDB 多数据中心部署 <[http://www.mongodb.com/lp/white-paper/multi-dc?jmp=docs](http://www.mongodb.com/lp/white-paper/multi-dc?jmp=docs)>`_ 71 | - ` 在线讲座:多数据中心部署 <[https://www.mongodb.com/presentations/webinar-multi-data-center-deployment?jmp=docs](https://www.mongodb.com/presentations/webinar-multi-data-center-deployment?jmp=docs)>`_ 72 | 73 | ← [Deploy Sharded Cluster using Ranged Sharding](http://www.mongoing.com/docs/tutorial/deploy-sharded-cluster-ranged-sharding.html)[Manage Shard Zones](http://www.mongoing.com/docs/tutorial/manage-shard-zone.html) → -------------------------------------------------------------------------------- /shell/README.md: -------------------------------------------------------------------------------- 1 | # `mongo` Shell 工具 2 | 3 | 本页索引: 4 | 5 | * [介绍](#介绍) 6 | * [启动 `mongo`Shell](#启动-mongo-shell) 7 | * [使用 `mongo` Shell 工作](#使用mongo-shell-工作) 8 | * [Tab 补全及其他快捷键](#tab-补全及其他快捷键) 9 | * [Exit](#exit) 10 | 11 | ## 介绍 12 | 13 | [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) shell 是一个基于 JavaScript 语言的 MongoDB 交互工具. 你可以使用 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell 来查询和更新数据也可以执行管理员操作. 14 | 15 | 同时 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) shell 也是 [MongoDB distributions](http://www.mongodb.org/downloads) 的一个组件. 只要你 [安装并且启动了 MongoDB](https://docs.mongodb.com/manual/installation/), 就可以通过 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell 连接到你运行中的 MongoDB 实例. 16 | 17 | 在 [MongoDB 手册](https://elemefe.gitbooks.io/mongodb/content/) 中的大部分例子都是使用 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) shell; 此外, 许多[驱动](https://docs.mongodb.com/manual/applications/drivers/) 也提供了相似的工具. 18 | 19 | ## 启动 `mongo` Shell 20 | 21 | **重要** 22 | 23 | 在试图启用 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell 之前确保 MongoDB 是运行的. 24 | 25 | 要启动 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell 并连接上运行在 **localhost** 和 **默认端口** 的 [MongoDB](https://docs.mongodb.com/manual/reference/program/mongod/) 实例: 26 | 27 | 1. 打开命令行工具, 找到你 `<存放mongodb工具的目录>`: 28 | 29 | ```bash 30 | cd <存放mongodb工具的目录> 31 | ``` 32 | 33 | 2. 输入`./bin/mongo` 来启动 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo): 34 | 35 | ```bash 36 | ./bin/mongo 37 | ``` 38 | 39 | 如果你已经把 `<存放mongodb工具的目录>/bin` 添加到 `PATH` 环境变量中, 就可以直接输入 `mongo` 不用输入 `./bin/mongo`. 40 | 41 | ### 选项 42 | 43 | 当你不加任何参数运行 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo), 那么 [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell 将会试图连接运行在 `localhost` 且端口是 `27017` 的 MongoDB 实例. 要指定一个其他 host 或者 port, 或者其他选项, 参见[启动 mongo 实例](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-usage-examples)和[mongo 引用](https://docs.mongodb.com/manual/reference/program/mongo/), 其中提供了详细的可用选项. 44 | 45 | ### `.mongorc.js` 文件 46 | 47 | 在启动时, [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 检查用户的 [`HOME`](https://docs.mongodb.com/manual/reference/program/mongo/#envvar-HOME) 目录下一个名为 [.mongorc.js](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-mongorc-file) 的 JavaScript 文件. 如果文件存在, [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 会在显示提示符之前第一时间加载 `.mongorc.js` 的内容. 当你使用 shell 来运行一个 JavaScript 文件或者表达式, 以及在命令行使用 `--eval` 选项或者指定一个 [.js 文件让 mongo 运行](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-shell-file)时, [`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 会在 JavaScript 执行结束后读取 `.mongorc.js` 文件. 你也可以通过使用 [`--norc`](https://docs.mongodb.com/manual/reference/program/mongo/#cmdoption-norc) 选项阻止 `.mongorc.js` 被加载. 48 | 49 | ## 使用`mongo` Shell 工作 50 | 51 | 要查看当前使用的数据库库, 你可以输入 `db`: 52 | 53 | ``` 54 | db 55 | ``` 56 | 57 | The operation should return`test`, which is the default database. To switch databases, issue the`use`helper, as in the following example: 58 | 59 | ``` 60 | use 61 | ``` 62 | 63 | To list the available databases, use the helper`showdbs`. See also[`db.getSiblingDB()`](https://docs.mongodb.com/manual/reference/method/db.getSiblingDB/#db.getSiblingDB)method to access a different database from the current database without switching your current database context \(i.e.`db`\). 64 | 65 | You can switch to non-existing databases. When you first store data in the database, such as by creating a collection, MongoDB creates the database. For example, the following creates both the database`myNewDatabase`and the[collection](https://docs.mongodb.com/manual/reference/glossary/#term-collection)`myCollection`during the[`insertOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne)operation: 66 | 67 | ``` 68 | use myNewDatabase 69 | db.myCollection.insertOne( { x: 1 } ); 70 | ``` 71 | 72 | The[`db.myCollection.insertOne()`](https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne)is one of the[methods available in the mongo shell](https://docs.mongodb.com/manual/reference/method/). 73 | 74 | * `db` 75 | refers to the current database. 76 | * `myCollection` 77 | is the name of the collection. 78 | 79 | If the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell does not accept the name of a collection, you can use the alternative[`db.getCollection()`](https://docs.mongodb.com/manual/reference/method/db.getCollection/#db.getCollection)syntax. For instance, if a collection name contains a space or hyphen, starts with a number, or conflicts with a built-in function: 80 | 81 | ``` 82 | db.getCollection("3 test").find() 83 | db.getCollection("3-test").find() 84 | db.getCollection("stats").find() 85 | ``` 86 | 87 | The[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell prompt has a limit of 4095 codepoints for each line. If you enter a line with more than 4095 codepoints, the shell will truncate it. 88 | 89 | For more documentation of basic MongoDB operations in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, see: 90 | 91 | * [Getting Started Guide](https://docs.mongodb.com/getting-started/shell) 92 | * [Insert Documents](https://docs.mongodb.com/manual/tutorial/insert-documents/) 93 | * [Query Documents](https://docs.mongodb.com/manual/tutorial/query-documents/) 94 | * [Update Documents](https://docs.mongodb.com/manual/tutorial/update-documents/) 95 | * [Delete Documents](https://docs.mongodb.com/manual/tutorial/remove-documents/) 96 | * [mongo Shell Methods](https://docs.mongodb.com/manual/reference/method/) 97 | 98 | ### Format Printed Results 99 | 100 | The[`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)method returns a[cursor](https://docs.mongodb.com/manual/reference/glossary/#term-cursor)to the results; however, in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, if the returned cursor is not assigned to a variable using the`var`keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell will prompt`Typeit`to iterate another 20 times. 101 | 102 | To format the printed result, you can add the`.pretty()`to the operation, as in the following: 103 | 104 | ```js 105 | db.myCollection.find().pretty() 106 | ``` 107 | 108 | In addition, you can use the following explicit print methods in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 109 | 110 | * `print()`to print without formatting 111 | * `print(tojson())`to print with [JSON](https://docs.mongodb.com/manual/reference/glossary/#term-json) formatting and equivalent to `printjson()` 112 | * `printjson()` to print with [JSON](https://docs.mongodb.com/manual/reference/glossary/#term-json) formatting and equivalent to `print(tojson())` 113 | 114 | For more information and examples on cursor handling in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, see[Iterate a Cursor in the mongo Shell](https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/). See also[Cursor Help](https://docs.mongodb.com/manual/tutorial/access-mongo-shell-help/#mongo-shell-help-cursor)for list of cursor help in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell. 115 | 116 | ### Multi-line Operations in the`mongo`Shell 117 | 118 | If you end a line with an open parenthesis \(`'('`\), an open brace \(`'{'`\), or an open bracket \(`'['`\), then the subsequent lines start with ellipsis \(`"..."`\) until you enter the corresponding closing parenthesis \(`')'`\), the closing brace \(`'}'`\) or the closing bracket \(`']'`\). The[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell waits for the closing parenthesis, closing brace, or the closing bracket before evaluating the code, as in the following example: 119 | 120 | ``` 121 | > if ( x > 0 ) { 122 | ... count++; 123 | ... print (x); 124 | ... } 125 | ``` 126 | 127 | You can exit the line continuation mode if you enter two blank lines, as in the following example: 128 | 129 | ``` 130 | > if (x > 0 131 | ... 132 | ... 133 | > 134 | ``` 135 | 136 | ## Tab 补全及其他快捷键 137 | 138 | The[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell supports keyboard shortcuts. For example, 139 | 140 | * Use the up/down arrow keys to scroll through command history. See[.dbshell](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-dbshell-file)documentation for more information on the`.dbshell`file. 141 | 142 | * Use``to autocomplete or to list the completion possibilities, as in the following example which uses``to complete the method name starting with the letter`'c'`: 143 | 144 | ```js 145 | db.myCollection.c 146 | ``` 147 | 148 | Because there are many collection methods starting with the letter`'c'`, the``will list the various methods that start with`'c'`. 149 | 150 | For a full list of the shortcuts, see[Shell Keyboard Shortcuts](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-keyboard-shortcuts) 151 | 152 | ## Exit 153 | 154 | To exit the shell, type`quit()`or use the``shortcut. 155 | 156 | SEE ALSO 157 | 158 | * [Getting Started Guide](https://docs.mongodb.com/getting-started/shell) 159 | * [`mongoReferencePage`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo) 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /shell/configure.md: -------------------------------------------------------------------------------- 1 | # Configure the`mongo`Shell 2 | 3 | On this page 4 | 5 | * [Customize the Prompt](https://docs.mongodb.com/manual/tutorial/configure-mongo-shell/#customize-the-prompt) 6 | * [Use an External Editor in the`mongo`Shell](https://docs.mongodb.com/manual/tutorial/configure-mongo-shell/#use-an-external-editor-in-the-mongo-shell) 7 | * [Change the`mongo`Shell Batch Size](https://docs.mongodb.com/manual/tutorial/configure-mongo-shell/#change-the-mongo-shell-batch-size) 8 | 9 | ## Customize the Prompt 10 | 11 | You may modify the content of the prompt by setting the variable`prompt`in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell. The`prompt`variable can hold strings as well as JavaScript code. If`prompt`holds a function that returns a string,[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)can display dynamic information in each prompt. 12 | 13 | You can add the logic for the prompt in the[.mongorc.js](https://docs.mongodb.com/manual/reference/program/mongo/#mongo-mongorc-file)file to set the prompt each time you start up the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell. 14 | 15 | ### Customize Prompt to Display Number of Operations 16 | 17 | For example,to create a[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell prompt with the number of operations issued in the current session, define the following variables in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 18 | 19 | ``` 20 | cmdCount 21 | = 22 | 1 23 | ; 24 | prompt 25 | = 26 | function 27 | () 28 | { 29 | return 30 | ( 31 | cmdCount 32 | ++ 33 | ) 34 | + 35 | " 36 | > 37 | " 38 | ; 39 | } 40 | ``` 41 | 42 | The prompt would then resemble the following: 43 | 44 | ``` 45 | 1 46 | > 47 | 2 48 | > 49 | 3 50 | > 51 | ``` 52 | 53 | ### Customize Prompt to Display Database and Hostname 54 | 55 | To create a[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell prompt in the form of`@$`, define the following variables: 56 | 57 | ``` 58 | host 59 | = 60 | db 61 | . 62 | serverStatus 63 | (). 64 | host 65 | ; 66 | prompt 67 | = 68 | function 69 | () 70 | { 71 | return 72 | db 73 | + 74 | "@" 75 | + 76 | host 77 | + 78 | "$ " 79 | ; 80 | } 81 | ``` 82 | 83 | The prompt would then resemble the following: 84 | 85 | ``` 86 | test@myHost1$ 87 | 88 | ``` 89 | 90 | ### Customize Prompt to Display Up Time and Document Count 91 | 92 | To create a[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell prompt that contains the system up time_and_the number of documents in the current database, define the following`prompt`variable in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell: 93 | 94 | ``` 95 | prompt 96 | = 97 | function 98 | () 99 | { 100 | return 101 | "Uptime:" 102 | + 103 | db 104 | . 105 | serverStatus 106 | (). 107 | uptime 108 | + 109 | " Documents:" 110 | + 111 | db 112 | . 113 | stats 114 | (). 115 | objects 116 | + 117 | " 118 | > 119 | " 120 | ; 121 | } 122 | ``` 123 | 124 | The prompt would then resemble the following: 125 | 126 | ``` 127 | Uptime 128 | : 129 | 5897 130 | Documents 131 | : 132 | 6 133 | > 134 | ``` 135 | 136 | ## Use an External Editor in the`mongo`Shell 137 | 138 | You can use your own editor in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell by setting the[`EDITOR`](https://docs.mongodb.com/manual/reference/program/mongo/#envvar-EDITOR)environment variable_before_starting the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell. 139 | 140 | ``` 141 | export 142 | EDITOR 143 | = 144 | vim 145 | mongo 146 | 147 | ``` 148 | 149 | Once in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, you can edit with the specified editor by typing`edit`or`edit`, as in the following example: 150 | 151 | 1. Define a function`myFunction`: 152 | 153 | ``` 154 | function 155 | myFunction 156 | () 157 | { 158 | } 159 | ``` 160 | 161 | 2. Edit the function using your editor: 162 | 163 | ``` 164 | edit 165 | myFunction 166 | ``` 167 | 168 | The command should open the`vim`edit session. When finished with the edits, save and exit`vim`edit session. 169 | 170 | 3. In the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, type`myFunction`to see the function definition: 171 | 172 | ``` 173 | myFunction 174 | ``` 175 | 176 | The result should be the changes from your saved edit: 177 | 178 | ``` 179 | function 180 | myFunction 181 | () 182 | { 183 | print 184 | ( 185 | "This was edited" 186 | ); 187 | } 188 | ``` 189 | 190 | NOTE 191 | 192 | As[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell interprets code edited in an external editor, it may modify code in functions, depending on the JavaScript compiler. For[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)may convert`1+1`to`2`or remove comments. The actual changes affect only the appearance of the code and will vary based on the version of JavaScript used but will not affect the semantics of the code. 193 | 194 | ## Change the`mongo`Shell Batch Size 195 | 196 | The[`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)method is the JavaScript method to retrieve documents from a[collection](https://docs.mongodb.com/manual/reference/glossary/#term-collection). The[`db.collection.find()`](https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find)method returns a[cursor](https://docs.mongodb.com/manual/reference/glossary/#term-cursor)to the results; however, in the[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell, if the returned cursor is not assigned to a variable using the`var`keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell will prompt`Typeit`to iterate another 20 times. 197 | 198 | You can set the`DBQuery.shellBatchSize`attribute to change the number of documents from the default value of`20`, as in the following example which sets it to`10`: 199 | 200 | ``` 201 | DBQuery 202 | . 203 | shellBatchSize 204 | = 205 | 10 206 | ; 207 | ``` 208 | 209 | 210 | 211 | -------------------------------------------------------------------------------- /text-search/README.md: -------------------------------------------------------------------------------- 1 | # Text Search 2 | 3 | On this page 4 | 5 | * [Overview](https://docs.mongodb.com/manual/text-search/#overview) 6 | * [Example](https://docs.mongodb.com/manual/text-search/#example) 7 | * [Language Support](https://docs.mongodb.com/manual/text-search/#language-support) 8 | 9 | ## Overview 10 | 11 | MongoDB supports query operations that perform a text search of string content. To perform text search, MongoDB uses a[text index](https://docs.mongodb.com/manual/core/index-text/#index-feature-text)and the[`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text)operator. 12 | 13 | NOTE 14 | 15 | [Views](https://docs.mongodb.com/manual/core/views/)do not support text search. 16 | 17 | ## Example 18 | 19 | This example demonstrates how to build a text index and use it to find coffee shops, given only text fields. 20 | 21 | Create a collection`stores`with the following documents: 22 | 23 | ```js 24 | db.stores.insert( 25 | [ 26 | { _id: 1, name: "Java Hut", description: "Coffee and cakes" }, 27 | { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" }, 28 | { _id: 3, name: "Coffee Shop", description: "Just coffee" }, 29 | { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" }, 30 | { _id: 5, name: "Java Shopping", description: "Indonesian goods" } 31 | ] 32 | ) 33 | ``` 34 | 35 | ### Text Index 36 | 37 | MongoDB provides[text indexes](https://docs.mongodb.com/manual/core/index-text/#index-feature-text)to support text search queries on string content.`text`indexes can include any field whose value is a string or an array of string elements. 38 | 39 | To perform text search queries, you must have a`text`index on your collection. A collection can only have**one**text search index, but that index can cover multiple fields. 40 | 41 | For example you can run the following in a[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell to allow text search over the`name`and`description`fields:db 42 | 43 | ```js 44 | db.stores.createIndex( { name: "text", description: "text" } ) 45 | ``` 46 | 47 | ### `$text`Operator 48 | 49 | Use the[`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text)query operator to perform text searches on a collection with a[text index](https://docs.mongodb.com/manual/core/index-text/#index-feature-text). 50 | 51 | [`$text`](https://docs.mongodb.com/manual/reference/operator/query/text/#op._S_text)will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical`OR`of all such tokens in the search string. 52 | 53 | For example, you could use the following query to find all stores containing any terms from the list “coffee”, “shop”, and “java”: 54 | 55 | ```js 56 | db.stores.find( { $text: { $search: "java coffee shop" } } ) 57 | ``` 58 | 59 | #### Exact Phrase 60 | 61 | You can also search for exact phrases by wrapping them in double-quotes. For example, the following will find all documents containing “java” or “coffee shop”: 62 | 63 | ```js 64 | db.stores.find( { $text: { $search: "java \"coffee shop\"" } } ) 65 | ``` 66 | 67 | #### Term Exclusion 68 | 69 | To exclude a word, you can prepend a “`-`” character. For example, to find all stores containing “java” or “shop” but not “coffee”, use the following:db 70 | 71 | ```js 72 | db.stores.find( { $text: { $search: "java shop -coffee" } } ) 73 | ``` 74 | 75 | #### Sorting 76 | 77 | MongoDB will return its results in unsorted order by default. However, text search queries will compute a relevance score for each document that specifies how well a document matches the query. 78 | 79 | To sort the results in order of relevance score, you must explicitly project the[`$meta`](https://docs.mongodb.com/manual/reference/operator/projection/meta/#proj._S_meta)`textScore`field and sort on it: 80 | 81 | ```js 82 | db.stores.find( 83 | { $text: { $search: "java coffee shop" } }, 84 | { score: { $meta: "textScore" } } 85 | ).sort( { score: { $meta: "textScore" } } ) 86 | ``` 87 | 88 | Text search is also available in the aggregation pipeline. 89 | 90 | ## Language Support 91 | 92 | MongoDB supports text search for various languages. See[Text Search Languages](https://docs.mongodb.com/manual/reference/text-search-languages/)for a list of supported languages. 93 | 94 | -------------------------------------------------------------------------------- /text-search/indexes.md: -------------------------------------------------------------------------------- 1 | # Text Indexes 2 | 3 | MongoDB provides[text indexes](https://docs.mongodb.com/manual/core/index-text/#index-feature-text)to support text search queries on string content.`text`indexes can include any field whose value is a string or an array of string elements. 4 | 5 | To perform text search queries, you must have a`text`index on your collection. A collection can only have**one**text search index, but that index can cover multiple fields. 6 | 7 | For example you can run the following in a[`mongo`](https://docs.mongodb.com/manual/reference/program/mongo/#bin.mongo)shell to allow text search over the`name`and`description`fields: 8 | 9 | ```js 10 | db.stores.createIndex( { name: "text", description: "text" } ) 11 | 12 | ``` 13 | 14 | See the[Text Indexes](https://docs.mongodb.com/manual/core/index-text/)section for a full reference on text indexes, including behavior, tokenization, and properties. 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------