MongoDB

Edit

MongoDB 手册


第一章 Introduction


MongoDB入门学习目录

Databases

MongoDB stores BSON documents, i.e. data records, in collections; the collections in databases.

  • 选择DB

use mdb
  • 创建DB

Mongodb当一个DB不存在时,默认存储一条数据即可创建DB

use noexistdb db.myNewCollection1.insert( { x: 1 } )

The insert() operation creates both the database myNewDB and the collection myNewCollection1 if they do not already exist

  • 1. DB命名规范

DataName Name Case Sensitivity,不分大小写

Mongodb中DBName名称大小写不敏感,所以不能单纯的通过大小写来区分DBName

  • 2. Restrictions on Database Names for Windows

如果Mongo运行在Windows平台,命名中不能包括如下特别字符,Also database names cannot contain the null character.并且不能带null字符

/\. "$*<>:|?` 
  • 3. Restrictions on Database Names for Unix and Linux Systems

如果MongoDB运行在类UNIX或LINUX系统,那么不能包括如下特殊字符

/\. "$ 
  • 4. Length of Database Names

不能为空且小于64个字符

  • 5. Restriction on Collection Names

Collections必须以_或字母开头,但不能包括如下特殊字符

  • contain the$.

  • be an empty string (e.g. “”).

  • contain the null character.

  • begin with thesystem.prefix. (Reserved for internal use.)

If your collection name includes special characters, such as the underscore character, then to access the collection use the db.getCollection() method in the mongo shell or a similar method for your driver.

The maximum length of the collection namespace, which includes the database name, the dot (.) separator, and the collection name (i.e. .), is 120 bytes.

  • 6. Restrictions on Field Names

不能包括.或空字符。 不能以$开头。原理请参考 How does MongoDB address SQL or Query injection?
原文内容也可参考如下:
MongoDB represents queries as BSON objects. Typically client libraries provide a convenient, injection free, process to build these objects. Consider the following C++ example:

BSONObj my_query = BSON( "name" << a_name ); auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", my_query); 

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.

感觉官方的解释不是特别清楚,这里谈下个人的理解:
Mongo query函数底层默认不对正则或者.,{特殊元字符做处理,所以导致不能包括特殊字符

Collections

Mongo默认是把所有的的文档(Documents)以BSON格式存储在集合(collections)。Collections类似于传统数据库中的表(tables)。

  • 创建Collections

如果 collections 事先不存在,Mongo默认会事先创建当你第一次存储数据时

db.myNewCollection2.insert( { x: 1 }
db.myNewCollection3.createIndex( { y: 1 } )

Both the insert() and the createIndex() operations create their respective collection if they do not already exist.
insert() 和 createIndex() 均会分别建立对应的集合(collections)

  • Explicit Creation

MongoDB默认也明确提供了新建集合工具,同时具有丰富的参数配置。MongoDB provides the db.createCollection() method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

Documents

Documents 按如下顺序介绍

  • Document Structure

  • Dot Notation

  • Document Limitations

  • Other Uses of the Document Structure

  • Additional Resources

Document Structure


MongoDB中一条记录就是一个document,MongoDB的数据结构以BSON方式存放,相比JSON而言BSON可以存放更为复杂的数据样式内容。更多关于BSON的内容可参考。一条记录包涵多对列和值匹配对的数据结构,MongoDB类似JSON Objects. 如下是例子

{
   "_id" : ObjectId("54c955492b7c8eb21818bd09"),
   "address" : {
      "street" : "2 Avenue",
      "zipcode" : "10075",
      "building" : "1480",
      "coord" : [ -73.9557413, 40.7720266 ]
   },
   "borough" : "Manhattan",
   "cuisine" : "Italian",
   "grades" : [
      {
         "date" : ISODate("2014-10-01T00:00:00Z"),
         "grade" : "A",
         "score" : 11      },
      {
         "date" : ISODate("2014-01-16T00:00:00Z"),
         "grade" : "B",
         "score" : 17      }
   ],
   "name" : "Vella",
   "restaurant_id" : "41704620" }
  • Document Structure

MongoDB的数据结构多以kv的方式存放,如下样式。

{
   field1: value1,
   field2: value2,
   field3: value3,
   ...
   fieldN: valueN
}

其中的value可以是任意的BSON数据结构,可以是other documents,arrays, andarrays of documents.如:

var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

上面的这个案例包括多个数据结构类似

  • _idholds an ObjectId.

  • nameholds an embedded document that contains the fieldsfirstandlast.

  • birthanddeathhold values of the Date type.

  • contribsholds an array of strings.

  • viewsholds a value of the NumberLong type.

Dot Notation


MongoDB 使用.来访问documents中列的元素,数组index默认从0开始。

  • 数组元素访问

{
   ...
   contribs: [ "Turing machine", "Turing test", "Turingery" ],
   ...
}

如我们希望访问contribs第三个元素,则用contribs.2即可

{
   ...
   name: { first: "Alan", last: "Turing" },
   ...
}

如希望取name的last值,则 “name.last”即可

Document Limitations

  • Document Size Limit
    最大的BSON值为 16M

  • Document Field Order
    MongoDB以写顺序保存Document,除以下情况外:
    – The _id field is always the first field in the document.
    – Updates that include renaming of field names may result in the reordering of fields in the document.

Other Uses of the Document Structure

第二章 部署安装


  • 支持的平台

Platform 3.2 3 2.6 2.4 2.2
Amazon Linux
Debian 7
Fedora 8+
RHEL/CentOS 6.2+
RHEL/CentOS 7.0+
SLES 11
SLES 12
Solaris 64-bit
Ubuntu 12.04
Ubuntu 14.04
Microsoft Azure
Windows Vista/Server 2008R2/2012+
OSX 10.7+
  • 不建议32位系统,有很多限制

    • 3.0版本的mongo不再支持32位系统,即32位系统不支持WiredTiger 存储引擎

    • 32位系统因文件句柄限制的原因默认disable journaling

    • 另外,32位系统支持mongodb的最大容量为2GB,这容量还包括数据,indexes,

32位系统的详细限制可以参考这里:
Blog Post: 32-bit Limitations

  • MongoDB社区版的安装

MongoDB有Enterprise和Community两个版本,具体差别可以参考这里,更详细内容请参考官网

  • MongoDB Enterprise Server is the commercial edition of MongoDB.

    • In-memory Storage Engine (in beta) – deliver high throughput and predictable low latency

    • Encrypted Storage Engine – encrypt your data at rest

    • Advanced Security – secure your data with LDAP and Kerberos authentication, and comprehensive auditing

    • Commercial License – to meet your development and distribution requirements

功能区别对比请参考如下:

版本特性 社区版本 企业版本
JSON数据模型、自由模式 支持 支持
水平扩展的自动分片功能 支持 支持
内置副本以及高可用性 支持 支持
完整的、可扩展的索引支撑 支持 支持
丰富的文档查询功能 支持 支持
快速的文档内更新 支持 支持
聚合框架和MapReduce 支持 支持
使用GridFS存储大量多媒体数据 支持 支持
文本搜索 支持 支持
云、预置和混合部署 支持 支持
基于角色的权限控制 支持 支持
基于Kerberos先进的安全认证 不支持 支持
预置监控 不支持 支持
支持SNMP 不支持 支持
操作系统认证 不支持 支持

因为企业版是收费的,所以我们安装的是社区版。

Install MongoDB Community Edition on Red Hat Enterprise or CentOS Linux

package function
mongodb-org A metapackage that will automatically install the four component packages listed below.
mongodb-org-server Contains the mongod daemon and associated configuration and init scripts.
mongodb-org-mongos Contains the mongos daemon.
mongodb-org-shell Contains the mongo shell.
mongodb-org-tools Contains the following MongoDB tools: mongoimport bsondump, mongodump, mongoexport, mongofiles, mongooplog, mongoperf, mongorestore, mongostat, and mongotop.

MongoDB默认配置文件/etc/mongod.conf,bind_ip默认绑定127.0.0.1
默认安装好的 MongoDB附带启动脚本,/etc/rc.d/init.d/mongod

1. Import the MongoDB public key

rpm --import https://www.mongodb.org/static/pgp/server-3.2.asc 

2. Configure the package management system (yum)

编辑/etc/yum.repos.d/mongodb-org-3.2.repo,使用如下的 repository 文件:

[mongodb-org-3.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/ gpgcheck=1 enabled=1 

3. Install the MongoDB packages and associated tools

如果对版本没有要求,下面的命令默认安装最新稳定版本的MongoDB

yum install -y mongodb-org

如果希望指定版本安装,可以使用如下命令:

yum install -y mongodb-org-3.2.4 mongodb-org-server-3.2.4 mongodb-org-shell-3.2.4 mongodb-org-mongos-3.2.4 mongodb-org-tools-3.2.4 

如果每次update的时候不希望升级部分组件,可以配置/etc/yum.conf

exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools

4. Run MongoDB Community Edition

配置SELinux

IMPORTANT
You must configure SELinux to allow MongoDB to start on Red Hat Linux-based systems (Red Hat Enterprise Linux or CentOS Linux).

SELinux 的3种处理办法

  • 配置/etc/selinux/config关闭SELinux

SELINUX=disabled 
  • 设置 SELinux为 permissive 状态

SELINUX=permissive 
  • Enable SELinux,开放MongoDB的SELinux权限

semanage port -a -t mongod_port_t -p tcp 27017 

WARNING
On RHEL 7.0, if you change the data path, the default SELinux policies will prevent mongod from having write access on the new data path if you do not change the security context.

5. 运行MongoDB

  • Start MongoDB

    service mongod start 
  • 检查MongoDB是否启动成功

    [initandlisten] waiting for connections on port <port>
    

默认MongoDB端口号是 27017,同时注册MongoDB为开机启动

chkconfig mongod on 
  • Stop MongoDB

    service mongod stop 
  • Restart MongoDB

    service mongod restart
    
  • 使用Begin using MongoDB
    详细请参考文档

6. 卸载MongoDB

卸载是不可逆的,所以请注意保存数据

WARNING
This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.

  • STOP MongoDB

    service mongod stop 
  • Remove Packages

    yum erase $(rpm -qa | grep mongodb-org)
    
  • Remove Data Directories.

    sudo rm -r /var/log/mongodb
    sudo rm -r /var/lib/mongo 

第三章 Mongo Shell


1. Mongo Shell介绍

mongoshell 是一个java交互式工具连接MongoDB,我们可以使用mongoshell 查询升级数据。
mongoshell 是MongoDB发行版的插件之一,安装完MongoDB后,mongo可以直接使用

默认执行mongo命令,mongo默认连接 localhost 并连接 27017 端口。

mongo

2. 常用命令

a> 显示当时db名

db 

如上命令其它会默认返回 test,这是初次连接默认DBName。 使用 use 来切换DB,不切换DB直接查看其它DB信息可以使用db.getSiblingDB()

use <database>

列出现有所有DB

show dbs
  • 格式化输出结果Format Printed Results
    db.collection.find() 命令作用是返回数据查询结果,但如果数据结构默认没有使用 K/V 结构,则游标会自动重复查询配置的结果重复输出20次。我们可以通过.pretty()友好输出结果。

    db.myCollection.find().pretty() 
  • 命令执行

    - 命令可以分行执行
    - 类似python,如果以`(`,`[`,`{`等开始,会等到另外一半匹配后才能继续,否则报错
    - 和Linux系统命令一样具有补全功能
    

b> Insert

Insert Data with the mongo Shell,本节将按如下顺序介绍


使用insert()方法可以增加documents到MongoDB的collections,如果事先没有,则MongoDB会事先创建


use test 

默认连接MongoDB后连接的test库


插入一条documents到名为restaurants的collection集合,命令默认为创建 restaurants 集合,如果事先不存在该 collections的话。

db.restaurants.insert(
   {
      "address" : {
         "street" : "2 Avenue",
         "zipcode" : "10075",
         "building" : "1480",
         "coord" : [ -73.9557413, 40.7720266 ],
      },
      "borough" : "Manhattan",
      "cuisine" : "Italian",
      "grades" : [
         {
            "date" : ISODate("2014-10-01T00:00:00Z"),
            "grade" : "A",
            "score" : 11         },
         {
            "date" : ISODate("2014-01-16T00:00:00Z"),
            "grade" : "B",
            "score" : 17         }
      ],
      "name" : "Vella",
      "restaurant_id" : "41704620"   }
)

执行成功后,MongoDB默认返回WriteResult函数结果返回

WriteResult({ "nInserted" : 1 }) 

其它信息可继续了解 insert()  Documents

c> Find

Find功能介绍会从如下方面开始(Find or Query Data with the mongo Shell)

  • Overview

  • Prerequisites

  • Query for All Documents in a Collection

  • Specify Equality Conditions

  • Specify Conditions with Operators

  • Combine Conditions

  • Sort Query Results

  • Additional Information

  • Overview


使用find() 从 MongoDB集合查找所需数据

默认MongoDB返回所有查找到的数据,我们可以通过 filter(过滤器) 和 条件 (criteria ) 或者附加执行条件给find()方法实现精准查询。

  • Prerequisites


进入指定数据库

use test 
  • Query for All Documents in a Collection


find()方法默认返回所有配置的执行结果,

db.restaurants.find()
  • Query by a Top Level Field

  • Query by a Field in an Embedded Document


两部分内容合为一起作为 MongoDB 的条件查询

db.restaurants.find( { "borough": "Manhattan" } )
db.restaurants.find( { "address.zipcode": "10075" } )

数组内容查询

db.restaurants.find( { "grades.grade": "B" } )
  • Specify Conditions with Operators(逻辑条件匹配查询)

{ <field1>: { <operator1>: <value1> } }

Greater Than Operator ($gt)

db.restaurants.find( { "grades.score": { $gt: 30 } } )

Less Than Operator ($lt)

db.restaurants.find( { "grades.score": { $lt: 10 } } )

Logical AND

db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } )

Logical OR

db.restaurants.find(
   { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)
  • Sort Query Results


db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } ) 

1 表示升序
-1 表示降序

如上的例子表示
For example, the following operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the “address.zipcode” field in ascending order:

d> Update

  • Update Top-Level Fields


The following operation updates the first document with name equal to “Juni”, using the$setoperator to update the cuisine field and the$currentDateoperator to update the lastModified field with the current date.

db.restaurants.update(
    { "name" : "Juni" },
    {
      $set: { "cuisine": "American (New)" },
      $currentDate: { "lastModified": true }
    }
)
  • Update an Embedded Field


To update a field within an embedded document, use the dot notation. When using the dot notation, enclose the whole dotted field name in quotes. The following updates the street field in the embedded address document.

db.restaurants.update(
  { "restaurant_id" : "41156888" },
  { $set: { "address.street": "East 31st Street" } }
)
  • Update Multiple Documents(多变更|多document变更|批量变更)


By default, theupdate()method updates a single document. To update multiple documents, use the multi option in the update() method. The following operation updates all documents that have address.zipcode field equal to “10016” and cuisine field equal to “Other”, setting the cuisine field to “Category To Be Determined” and the lastModified field to the current date.

db.restaurants.update(
  { "address.zipcode": "10016", cuisine: "Other" },
  {
    $set: { cuisine: "Category To Be Determined" },
    $currentDate: { "lastModified": true }
  },
  { multi: true}
)
  • Replace a Document


To replace the entire document except for the _id field, pass an entirely new document as the second argument to theupdate()method. The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable. If you do include the _id field, it must be the same value as the existing value.

IMPORTANT
After the update, the document only contains the field or fields in the replacement document.

After the following update, the modified document will only contain the _id field, name field, the address field. i.e. the document will not contain the restaurant_id, cuisine, grades, and the borough fields.

db.restaurants.update(
   { "restaurant_id" : "41704620" },
   {
     "name" : "Vella 2",
     "address" : {
              "coord" : [ -73.9557413, 40.7720266 ],
              "building" : "1480",
              "street" : "2 Avenue",
              "zipcode" : "10075"     }
   }
)

e> Remove


remove() 方法接受指定条件后从集合(collections)移除文档记录(documents).

如需移除指定条件的documents,和query一样使用相同的语法和数据结构即可。

  • 移除所有符合条件的文档记录(documents.)Remove All Documents That Match a Condition

db.restaurants.remove( { "borough": "Manhattan" } )
  • 只移除一条记录Use the justOne Option

By default, the remove() method removes all documents that match the remove condition. Use the justOne option to limit the remove operation to only one of the matching documents.

db.restaurants.remove( { "borough": "Queens" }, { justOne: true } )
  • 删除所有记录(Remove All Documents)

该方法collections集合本身和indexes仍然保留,所以如果希望删除所有建议使用 drop

To remove all documents from a collection, pass an empty conditions document {} to the remove() method.

db.restaurants.remove( { } )
  • 删除集合 Drop a Collection

The remove all operation only removes the documents from the collection. The collection itself, as well as any indexes for the collection, remain. To remove all documents from a collection, it may be more efficient to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes. Use the drop() method to drop a collection, including any indexes.

db.restaurants.drop()

Upon successful drop of the collection, the operation returns true.

f> Aggregation

MongoDB支持数据聚合,如指定key分组并且计划总合或分组总合。

用法如下:

db.collection.aggregate( [ <stage1>, <stage2>, ... ] )
  • 指定列group by 分组并求和 Group Documents by a Field and Calculate Count

Use the$groupstage to group by a specified key. In the$groupstage, specify the group by key in the_idfield.$groupaccesses fields by the field path, which is the field name prefixed by a dollar sign$. The$groupstage can use accumulators to perform calculations for each group. The following example groups the documents in the restaurants collection by the borough field and uses the$sumaccumulator to count the documents for each group.

db.restaurants.aggregate(
   [
     { $group: { "_id": "$borough", "count": { $sum: 1 } } }
   ]
);

类似结果返回如下:

{ "_id" : "Staten Island", "count" : 969 }
{ "_id" : "Brooklyn", "count" : 6086 }
{ "_id" : "Manhattan", "count" : 10259 }
{ "_id" : "Queens", "count" : 5656 }
{ "_id" : "Bronx", "count" : 2338 }
{ "_id" : "Missing", "count" : 51 }
  • Filter and Group Documents


Use the$matchstage to filter documents.$matchuses the MongoDB query syntax. The following pipeline uses$matchto query the restaurants collection for documents with borough equal to “Queens” and cuisine equal to Brazilian. Then the$groupstage groups the matching documents by the address.zipcode field and uses the$sumaccumulator to calculate the count.$groupaccesses fields by the field path, which is the field name prefixed by a dollar sign$.

db.restaurants.aggregate(
   [
     { $match: { "borough": "Queens", "cuisine": "Brazilian" } },
     { $group: { "_id": "$address.zipcode" , "count": { $sum: 1 } } }
   ]
);

返回结果如下:

The result set consists of the following documents:

g. Indexes

Indexes主要用于提升查询效率。MongoDB默认创建索引_id当创建 collections时。

createIndex() 用于创建 Indexes 索引。使用方法如下:

{ <field1>: <type1>, ...}

使用1 为升序
使用-1为降序

  • 创建单列索引


Create an ascending index on the “cuisine” field of the restaurants collection.

db.restaurants.createIndex( { "cuisine": 1 } )

The method returns a document with the status of the operation.

{
  "createdCollectionAutomatically" : false,
  "numIndexesBefore" : 1,
  "numIndexesAfter" : 2,
  "ok" : 1 }
  • 创建混合索引 Create a compound index

MongoDB supports compound indexes which are indexes on multiple fields. The order of the fields determine how the index stores its keys. For example, the following operation creates a compound index on the “cuisine” field and the “address.zipcode” field. The index orders its entries first by ascending “cuisine” values, and then, within each “cuisine”, by descending “address.zipcode” values.

db.restaurants.createIndex( { "cuisine": 1, "address.zipcode": -1 } )

The method returns a document with the status of the operation.

{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 2,
   "numIndexesAfter" : 3,
   "ok" : 1 }

第四章 MongoDB用户及权限管理

To authenticate a user, MongoDB provides the db.auth() method.

MongoDB认证即可通过 mongo shell在命令行认证,也可以进行MongoDB后使用db.auth() 认证

MongoDB可以存在相同用户名的用户,但是要存在不同的库中。如果希望一个用户同时对多个库拥有权限,需要对该用户赋多个库的权限即可,而不是到对应的库创建相同的用户名。
The user’s name and authentication database serve as a unique identifier for that user. That is, if two users have the same name but are created in different databases, they are two separate users. If you intend to have a single user with permissions on multiple databases, create a single user with roles in the applicable databases instead of creating the user multiple times in different databases.

MongoDB默认也有很多内置用户如

Role Short Description
read Provides the ability to read data on all non-system collections and on the following system collections: system.indexes, system.js, and system.namespaces collections. For the specific privileges granted by the role, see read.
readWrite Provides all the privileges of the read role and the ability to modify data on all non-system collections and the system.js collections。 For the specific privileges granted by the role, see readWrite.

mongodb密码忘记

修改 mongodb 配置,将 auth = true 注释掉,或者改成 false

vim /etc/mongodb.conf          

重启 mongodb 服务

service mongodb restart 

连接mongo

mongo                          # 运行客户端(也可以去mongodb安装目录下运行这个) use admin                      # 切换到系统帐户表 db.system.users.find()         # 查看当前帐户(密码有加密过) db.system.users.remove({})     # 删除所有帐户 db.addUser('admin','password') # 添加新帐户 

恢复 auth = true

vim /etc/mongodb.conf  

重启 mongodb 服务

enter code here

client 连接方式

  • 指定数据连接

mongod --port 27017 --dbpath /data/db1 
  • 创建 administrator 用户

use admin db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
  • (重启mongo连接)Re-start the MongoDB instance with access control

mongod --auth --port 27017 --dbpath /data/db1 
  • 以管理员身份连接

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin" 
  • 或者进入mongo后使用如下命令连接

use admin
db.auth("myUserAdmin", "abc123" ) 

mongo shell命令集用法

Collection
Name Description
db.collection.aggregate() Provides access to the aggregation pipeline.
db.collection.bulkWrite() Provides bulk write operation functionality.
db.collection.count() Wraps count to return a count of the number of documents in a collection or matching a query.
db.collection.copyTo() Deprecated. Wraps eval to copy data between collections in a single MongoDB instance.
db.collection.createIndex() Builds an index on a collection.
db.collection.dataSize() Returns the size of the collection. Wraps the size field in the output of the collStats.
db.collection.deleteOne() Deletes a single document in a collection.
db.collection.deleteMany() Deletes multiple documents in a collection.
db.collection.distinct() Returns an array of documents that have distinct values for the specified field.
db.collection.drop() Removes the specified collection from the database.
db.collection.dropIndex() Removes a specified index on a collection.
db.collection.dropIndexes() Removes all indexes on a collection.
db.collection.ensureIndex() Deprecated. Use db.collection.createIndex().
db.collection.explain() Returns information on the query execution of various methods.
db.collection.find() Performs a query on a collection and returns a cursor object.
db.collection.findAndModify() Atomically modifies and returns a single document.
db.collection.findOne() Performs a query and returns a single document.
db.collection.findOneAndDelete() Finds a single document and deletes it.
db.collection.findOneAndReplace() Finds a single document and replaces it.
db.collection.findOneAndUpdate() Finds a single document and updates it.
db.collection.getIndexes() Returns an array of documents that describe the existing indexes on a collection.
db.collection.getShardDistribution() For collections in sharded clusters,db.collection.getShardDistribution() reports data ofchunk distribution.
db.collection.getShardVersion() Internal diagnostic method for shard cluster.
db.collection.group() Provides simple data aggregation function. Groups documents in a collection by a key, and processes the results. Use aggregate() for more complex data aggregation.
db.collection.insert() Creates a new document in a collection.
db.collection.insertOne() Inserts a new document in a collection.
db.collection.insertMany() Inserts several new document in a collection.
db.collection.isCapped() Reports if a collection is a capped collection.
db.collection.mapReduce() Performs map-reduce style data aggregation.
db.collection.reIndex() Rebuilds all existing indexes on a collection.
db.collection.replaceOne() Replaces a single document in a collection.
db.collection.remove() Deletes documents from a collection.
db.collection.renameCollection() Changes the name of a collection.
db.collection.save() Provides a wrapper around an insert() and update() to insert new documents.
db.collection.stats() Reports on the state of a collection. Provides a wrapper around thecollStats.
db.collection.storageSize() Reports the total size used by the collection in bytes. Provides a wrapper around the storageSize field of the collStats output.
db.collection.totalSize() Reports the total size of a collection, including the size of all documents and all indexes on a collection.
db.collection.totalIndexSize() Reports the total size used by the indexes on a collection. Provides a wrapper around the totalIndexSize field of the collStatsoutput.
db.collection.update() Modifies a document in a collection.
db.collection.updateOne() Modifies a single document in a collection.
db.collection.updateMany() Modifies multiple documents in a collection.
db.collection.validate() Performs diagnostic operations on a collection.
Cursor
Name Description
cursor.batchSize() Controls the number of documents MongoDB will return to the client in a single network message.
cursor.close() Close a cursor and free associated server resources.
cursor.comment() Attaches a comment to the query to allow for traceability in the logs and the system.profile collection.
cursor.count() Modifies the cursor to return the number of documents in the result set rather than the documents themselves.
cursor.explain() Reports on the query execution plan for a cursor.
cursor.forEach() Applies a JavaScript function for every document in a cursor.
cursor.hasNext() Returns true if the cursor has documents and can be iterated.
cursor.hint() Forces MongoDB to use a specific index for a query.
cursor.itcount() Computes the total number of documents in the cursor client-side by fetching and iterating the result set.
cursor.limit() Constrains the size of a cursor’s result set.
cursor.map() Applies a function to each document in a cursor and collects the return values in an array.
cursor.maxScan() Specifies the maximum number of items to scan; documents for collection scans, keys for index scans.
cursor.maxTimeMS() Specifies a cumulative time limit in milliseconds for processing operations on a cursor.
cursor.max() Specifies an exclusive upper index bound for a cursor. For use with cursor.hint()
cursor.min() Specifies an inclusive lower index bound for a cursor. For use with cursor.hint()
cursor.next() Returns the next document in a cursor.
cursor.noCursorTimeout() Instructs the server to avoid closing a cursor automatically after a period of inactivity.
cursor.objsLeftInBatch() Returns the number of documents left in the current cursor batch.
cursor.pretty() Configures the cursor to display results in an easy-to-read format.
cursor.readConcern() Specifies a read concern for a find() operation.
cursor.readPref() Specifies a read preference to a cursor to control how the client directs queries to areplica set.
cursor.returnKey() Modifies the cursor to return index keys rather than the documents.
cursor.showRecordId() Adds an internal storage engine ID field to each document returned by the cursor.
cursor.size() Returns a count of the documents in the cursor after applying skip() and limit()methods.
cursor.skip() Returns a cursor that begins returning results only after passing or skipping a number of documents.
cursor.snapshot() Forces the cursor to use the index on the _id field. Ensures that the cursor returns each document, with regards to the value of the _id field, only once.
cursor.sort() Returns results ordered according to a sort specification.
cursor.tailable() Marks the cursor as tailable. Only valid for cursors over capped collections.
cursor.toArray() Returns an array that contains all documents returned by the cursor.
Database
Name Description
db.cloneCollection() Copies data directly between MongoDB instances. WrapscloneCollection.
db.cloneDatabase() Copies a database from a remote host to the current host. Wraps clone.
db.commandHelp() Returns help information for a database command.
db.copyDatabase() Copies a database to another database on the current host. Wraps copydb.
db.createCollection() Creates a new collection. Commonly used to create a capped collection.
db.currentOp() Reports the current in-progress operations.
db.dropDatabase() Removes the current database.
db.eval() Deprecated. Passes a JavaScript function to the mongod instance for server-side JavaScript evaluation.
db.fsyncLock() Flushes writes to disk and locks the database to prevent write operations and assist backup operations. Wraps fsync.
db.fsyncUnlock() Allows writes to continue on a database locked with db.fsyncLock().
db.getCollection() Returns a collection object. Used to access collections with names that are not valid in the mongo shell.
db.getCollectionInfos() Returns collection information for all collections in the current database.
db.getCollectionNames() Lists all collections in the current database.
db.getLastError() Checks and returns the status of the last operation. Wraps getLastError.
db.getLastErrorObj() Returns the status document for the last operation. Wraps getLastError.
db.getLogComponents() Returns the log message verbosity levels.
db.getMongo() Returns the Mongo() connection object for the current connection.
db.getName() Returns the name of the current database.
db.getPrevError() Returns a status document containing all errors since the last error reset. Wraps getPrevError.
db.getProfilingLevel() Returns the current profiling level for database operations.
db.getProfilingStatus() Returns a document that reflects the current profiling level and the profiling threshold.
db.getReplicationInfo() Returns a document with replication statistics.
db.getSiblingDB() Provides access to the specified database.
db.help() Displays descriptions of common db object methods.
db.hostInfo() Returns a document with information about the system MongoDB runs on. Wraps hostInfo
db.isMaster() Returns a document that reports the state of the replica set.
db.killOp() Terminates a specified operation.
db.listCommands() Displays a list of common database commands.
db.loadServerScripts() Loads all scripts in the system.js collection for the current database into the shell session.
db.logout() Ends an authenticated session.
db.printCollectionStats() Prints statistics from every collection. Wraps db.collection.stats().
db.printReplicationInfo() Prints a report of the status of the replica set from the perspective of the primary.
db.printShardingStatus() Prints a report of the sharding configuration and the chunk ranges.
db.printSlaveReplicationInfo() Prints a report of the status of the replica set from the perspective of the secondaries.
db.repairDatabase() Runs a repair routine on the current database.
db.resetError() Resets the error message returned by db.getPrevError() andgetPrevError.
db.runCommand() Runs a database command.
db.serverBuildInfo() Returns a document that displays the compilation parameters for the mongodinstance. Wraps buildinfo.
db.serverCmdLineOpts() Returns a document with information about the runtime used to start the MongoDB instance. Wraps getCmdLineOpts.
db.serverStatus() Returns a document that provides an overview of the state of the database process.
db.setLogLevel() Sets a single log message verbosity level.
db.setProfilingLevel() Modifies the current level of database profiling.
db.shutdownServer() Shuts down the current mongod or mongos process cleanly and safely.
db.stats() Returns a document that reports on the state of the current database.
db.version() Returns the version of the mongod instance.
db.upgradeCheck() Performs a preliminary check for upgrade preparedness for a specific database or collection.
db.upgradeCheckAllDBs() Performs a preliminary check for upgrade preparedness for all databases and collections.
Query Plan Cache
Name Description
db.collection.getPlanCache() Returns an interface to access the query plan cache object and associated PlanCache methods for a collection.”
PlanCache.help() Displays the methods available for a collection’s query plan cache. Accessible through the plan cache object of a specific collection, i.e.db.collection.getPlanCache().help().
PlanCache.listQueryShapes() Displays the query shapes for which cached query plans exist. Accessible through the plan cache object of a specific collection, i.e.db.collection.getPlanCache().listQueryShapes().
PlanCache.getPlansByQuery() Displays the cached query plans for the specified query shape. Accessible through the plan cache object of a specific collection, i.e.db.collection.getPlanCache().getPlansByQuery().
PlanCache.clearPlansByQuery() Clears the cached query plans for the specified query shape. Accessible through the plan cache object of a specific collection, i.e.db.collection.getPlanCache().clearPlansByQuery()
PlanCache.clear() Clears all the cached query plans for a collection. Accessible through the plan cache object of a specific collection, i.e.db.collection.getPlanCache().clear().
Bulk Write Operation
Name Description
Bulk() Bulk operations builder.
db.collection.initializeOrderedBulkOp() Initializes a Bulk() operations builder for an ordered list of operations.
db.collection.initializeUnorderedBulkOp() Initializes a Bulk() operations builder for an unordered list of operations.
Bulk.insert() Adds an insert operation to a list of operations.
Bulk.find() Specifies the query condition for an update or a remove operation.
Bulk.find.removeOne() Adds a single document remove operation to a list of operations.
Bulk.find.remove() Adds a multiple document remove operation to a list of operations.
Bulk.find.replaceOne() Adds a single document replacement operation to a list of operations.
Bulk.find.updateOne() Adds a single document update operation to a list of operations.
Bulk.find.update() Adds a multi update operation to a list of operations.
Bulk.find.upsert() Specifies upsert: true for an update operation.
Bulk.execute() Executes a list of operations in bulk.
Bulk.getOperations() Returns an array of write operations executed in the Bulk()operations object.
Bulk.tojson() Returns a JSON document that contains the number of operations and batches in the Bulk() operations object.
Bulk.toString() Returns the Bulk.tojson() results as a string.
User Management
Name Description
db.auth() Authenticates a user to a database.
db.createUser() Creates a new user.
db.updateUser() Updates user data.
db.changeUserPassword() Changes an existing user’s password.
db.removeUser() Deprecated. Removes a user from a database.
db.dropAllUsers() Deletes all users associated with a database.
db.dropUser() Removes a single user.
db.grantRolesToUser() Grants a role and its privileges to a user.
db.revokeRolesFromUser() Removes a role from a user.
db.getUser() Returns information about the specified user.
db.getUsers() Returns information about all users associated with a database.
Role Management
Name Description
db.createRole() Creates a role and specifies its privileges.
db.updateRole() Updates a user-defined role.
db.dropRole() Deletes a user-defined role.
db.dropAllRoles() Deletes all user-defined roles associated with a database.
db.grantPrivilegesToRole() Assigns privileges to a user-defined role.
db.revokePrivilegesFromRole() Removes the specified privileges from a user-defined role.
db.grantRolesToRole() Specifies roles from which a user-defined role inherits privileges.
db.revokeRolesFromRole() Removes inherited roles from a role.
db.getRole() Returns information for the specified role.
db.getRoles() Returns information for all the user-defined roles in a database.
Replication
Name Description
rs.add() Adds a member to a replica set.
rs.addArb() Adds an arbiter to a replica set.
rs.conf() Returns the replica set configuration document.
rs.freeze() Prevents the current member from seeking election as primary for a period of time.
rs.help() Returns basic help text for replica set functions.
rs.initiate() Initializes a new replica set.
rs.printReplicationInfo() Prints a report of the status of the replica set from the perspective of the primary.
rs.printSlaveReplicationInfo() Prints a report of the status of the replica set from the perspective of the secondaries.
rs.reconfig() Re-configures a replica set by applying a new replica set configuration object.
rs.remove() Remove a member from a replica set.
rs.slaveOk() Sets the slaveOk property for the current connection. Deprecated. UsereadPref() and Mongo.setReadPref() to set read preference.
rs.status() Returns a document with information about the state of the replica set.
rs.stepDown() Causes the current primary to become a secondary which forces an election.
rs.syncFrom() Sets the member that this replica set member will sync from, overriding the default sync target selection logic.
Sharding
Name Description
sh._adminCommand() Runs a database command against the admin database, like db.runCommand(), but can confirm that it is issued against a mongos.
sh.getBalancerLockDetails() Reports on the active balancer lock, if it exists.
sh._checkFullName() Tests a namespace to determine if its well formed.
sh._checkMongos() Tests to see if the mongo shell is connected to a mongos instance.
sh._lastMigration() Reports on the last chunk migration.
sh.addShard() Adds a shard to a sharded cluster.
sh.addShardTag() Associates a shard with a tag, to support tag aware sharding.
sh.addTagRange() Associates range of shard keys with a shard tag, to support tag aware sharding.
sh.removeTagRange() Removes an association between a range shard keys and a shard tag. Use to manage tag aware sharding.
sh.disableBalancing() Disable balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.
sh.enableBalancing() Activates the sharded collection balancer process if previously disabled usingsh.disableBalancing().
sh.enableSharding() Enables sharding on a specific database.
sh.getBalancerHost() Returns the name of a mongos that’s responsible for the balancer process.
sh.getBalancerState() Returns a boolean to report if the balancer is currently enabled.
sh.help() Returns help text for the sh methods.
sh.isBalancerRunning() Returns a boolean to report if the balancer process is currently migrating chunks.
sh.moveChunk() Migrates a chunk in a sharded cluster.
sh.removeShardTag() Removes the association between a shard and a shard tag.
sh.setBalancerState() Enables or disables the balancer which migrates chunks between shards.
sh.shardCollection() Enables sharding for a collection.
sh.splitAt() Divides an existing chunk into two chunks using a specific value of the shard key as the dividing point.
sh.splitFind() Divides an existing chunk that contains a document matching a query into two approximately equal chunks.
sh.startBalancer() Enables the balancer and waits for balancing to start.
sh.status() Reports on the status of a sharded cluster, as db.printShardingStatus().
sh.stopBalancer() Disables the balancer and waits for any in progress balancing rounds to complete.
sh.waitForBalancer() Internal. Waits for the balancer state to change.
sh.waitForBalancerOff() Internal. Waits until the balancer stops running.
sh.waitForDLock() Internal. Waits for a specified distributed sharded cluster lock.
sh.waitForPingChange() Internal. Waits for a change in ping state from one of the mongos in the sharded cluster.
Subprocess
Name Description
clearRawMongoProgramOutput() For internal use.
rawMongoProgramOutput() For internal use.
run() For internal use.
runMongoProgram() For internal use.
runProgram() For internal use.
startMongoProgram() For internal use.
stopMongoProgram() For internal use.
stopMongoProgramByPid() For internal use.
stopMongod() For internal use.
waitMongoProgramOnPort() For internal use.
waitProgram() For internal use.
Constructors
Name Description
Date() Creates a date object. By default creates a date object including the current date.
UUID() Converts a 32-byte hexadecimal string to the UUID BSON subtype.
ObjectId() Returns an ObjectId.
ObjectId.getTimestamp() Returns the timestamp portion of an ObjectId.
ObjectId.toString() Displays the string representation of an ObjectId.
ObjectId.valueOf() Displays the str attribute of an ObjectId as a hexadecimal string.
WriteResult() Wrapper around the result set from write methods.
WriteResult.hasWriteError() Returns a boolean specifying whether the results includeWriteResult.writeError.
WriteResult.hasWriteConcernError() Returns a boolean specifying whether whether the results includeWriteResult.writeConcernError.
BulkWriteResult() Wrapper around the result set from Bulk.execute().
Connection
Name Description
Mongo.getDB() Returns a database object.
Mongo.getReadPrefMode() Returns the current read preference mode for the MongoDB connection.
Mongo.getReadPrefTagSet() Returns the read preference tag set for the MongoDB connection.
Mongo.setReadPref() Sets the read preference for the MongoDB connection.
Mongo.setSlaveOk() Allows operations on the current connection to read from secondary members.
Mongo() Creates a new connection object.
connect() Connects to a MongoDB instance and to a specified database on that instance.
Native
Name Description
cat() Returns the contents of the specified file.
version() Returns the current version of the mongo shell instance.
cd() Changes the current working directory to the specified path.
sleep() Suspends the mongo shell for a given period of time.
copyDbpath() Copies a local dbPath. For internal use.
resetDbpath() Removes a local dbPath. For internal use.
fuzzFile() For internal use to support testing.
getHostName() Returns the hostname of the system running the mongo shell.
getMemInfo() Returns a document that reports the amount of memory used by the shell.
hostname() Returns the hostname of the system running the shell.
_isWindows() Returns true if the shell runs on a Windows system; false if a Unix or Linux system.
listFiles() Returns an array of documents that give the name and size of each object in the directory.
load() Loads and runs a JavaScript file in the shell.
ls() Returns a list of the files in the current directory.
md5sumFile() The md5 hash of the specified file.
mkdir() Creates a directory at the specified path.
pwd() Returns the current directory.
quit() Exits the current shell session.
_rand() Returns a random number between 0 and 1.
removeFile() Removes the specified file from the local file system.
setVerboseShell() Configures the mongo shell to report operation timing.
_srand() For internal use.

MongoDB集群

MongoDB缺陷

ObjectId

ObjectId小巧,唯一,可快速生成,易于排序。ObjectId总共由12-bytes组成。其中前4 bytes是unix时间缀,代表该ObjectId的生成时间。

  • a 4-byte value representing the seconds since the Unix epoch,

  • a 3-byte machine identifier,

  • a 2-byte process id, and

  • a 3-byte counter, starting with a random value.

在MongoDB中,每个documents存储在collections需要一个唯一的_id,_id扮演的角色是主键。如果_id默认没有定义,则MongoDB默认使用ObjectId,ObjectId的创建时间也可以通过ObjectId.getTimestamp()获取。

原创文章,作者:renjin,如若转载,请注明出处:http://www.178linux.com/78741

(0)
renjinrenjin
上一篇 2014-11-12 23:26
下一篇 2015-01-16

相关推荐

  • 文本编辑器—sed

    一、sed介绍 sed 一种流式编辑器。一个流式编辑器通常对来自输入流(一个文件或者是管道的输入)的文本进行转换处理。在某些方面类似支持脚本编辑的编辑器,sed在多输入情况下只开放一个通道工作,因此更加效率。sed与其他编辑器最大的区别在于,能对管道输入的文本进行过滤处理。 二、sed工作机制 sed保持两个数据缓冲区:主要活动的模式空间,以及辅助性的保持空…

    Linux干货 2016-08-12
  • 大概认识linux

             linux简介 其实对Linux系统不是很了解,都是在百度和谷歌搜索出来,才发现Linux很多版本。各版本各优缺点。首先简单说下发展史,Linux在1991年10月5号(这是第一次正式向外公布的时间)在芬兰诞生,以后借助于Internet网络向全世界各地传播,由计算机爱好者的再次开发新功能和…

    Linux干货 2016-05-29
  • HAProxy

    HAProxy简介 HAProxy是免费、极速且可靠的用于为TCP和基于HTTP应用程序提供高可用、负载均衡和代理服务的解决方案,尤其适用于高负载且需要持久连接或7层处理机制的web站点。HAProxy还可以将后端的服务器与网络隔离,起到保护后端服务器的作用。HAProxy的负载均衡能力虽不如LVS,但也是相当不错,而且由于其工作在7层,可以对http请求报…

    2017-05-17
  • n28 第二周作业

    n28 第二周作业

    Linux干货 2017-12-09
  • 系统基础之shell脚本编程详解2

    shell脚本编程2:   在上节我们介绍了shell脚本编程,但只是介绍了基础的内容,下面将为大家介绍shell的脚本的高级用法,判断与循环.判断分为两种:if语句和case语句;循环分为三种:for语句,while语句,until语句,select语句 判断语句:  在脚本的编写中,我们要使用大量的数据和命令,但对于使用的数据,我们要…

    Linux干货 2016-08-19
  • 如何定义一个命令的别名,如何在命令中引用另一个命令的执行结果

    命令别名使用alias命令; ~]#alias NAME='COMMAND' 在一个命令中引用另一个命令的执行结果也是bash的特性之一,引用。 方法:$(COMMAND)

    Linux干货 2016-11-06