《MongoDB极简教程》第二章 MongoDB 基本命令(Shell)

MongoDB的所有请求都以命令的形式发出,支持的命令列表参考Database Commands

The mongo Shell: https://docs.mongodb.com/manual/mongo/

db是mongoDB的全局变量,持有当前数据库schema的引用。 首次进入客户端shell,敲入命令db

> db
test

看看当前数据库server的状态

> db.serverStatus()
{
    "host" : "jacks-MacBook-Air.local",
    "advisoryHostFQDNs" : [
        "jacks-macbook-air.local"
    ],
    "version" : "3.2.4",
    "process" : "mongod",
    "pid" : NumberLong(68),
    "uptime" : 616301,
    "uptimeMillis" : NumberLong(616300555),
    "uptimeEstimate" : 35411,
    "localTime" : ISODate("2017-03-20T05:42:48.260Z"),
    "asserts" : {
        "regular" : 0,
        "warning" : 0,
        "msg" : 0,
        "user" : 0,
        "rollovers" : 0
    },
    "connections" : {
        "current" : 2,
        "available" : 3274,
        "totalCreated" : NumberLong(6)
    },
    "extra_info" : {
        "note" : "fields vary by platform",
        "page_faults" : 4993
    },
    "globalLock" : {
        "totalTime" : NumberLong("616300534000"),
        "currentQueue" : {
            "total" : 0,
            "readers" : 0,
            "writers" : 0
        },
        "activeClients" : {
            "total" : 9,
            "readers" : 0,
            "writers" : 0
        }
    },
    "locks" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(1471174),
                "w" : NumberLong(2920),
                "W" : NumberLong(4)
            }
        },
        "Database" : {
            "acquireCount" : {
                "r" : NumberLong(734121),
                "w" : NumberLong(2901),
                "R" : NumberLong(4),
                "W" : NumberLong(19)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "r" : NumberLong(774729),
                "w" : NumberLong(2901)
            }
        },
        "Metadata" : {
            "acquireCount" : {
                "w" : NumberLong(1)
            }
        }
    },
    "network" : {
        "bytesIn" : NumberLong(1529),
        "bytesOut" : NumberLong(6719),
        "numRequests" : NumberLong(21)
    },
    "opcounters" : {
        "insert" : 0,
        "query" : 1,
        "update" : 0,
        "delete" : 0,
        "getmore" : 0,
        "command" : 22
    },
    "opcountersRepl" : {
        "insert" : 0,
        "query" : 0,
        "update" : 0,
        "delete" : 0,
        "getmore" : 0,
        "command" : 0
    },
    "storageEngine" : {
        "name" : "wiredTiger",
        "supportsCommittedReads" : true
    },
    "wiredTiger" : {
        "uri" : "statistics:",
        "LSM" : {
            "sleep for LSM checkpoint throttle" : 0,
            "sleep for LSM merge throttle" : 0,
            "rows merged in an LSM tree" : 0,
            "application work units currently queued" : 0,
            "merge work units currently queued" : 0,
            "tree queue hit maximum" : 0,
            "switch work units currently queued" : 0,
            "tree maintenance operations scheduled" : 0,
            "tree maintenance operations discarded" : 0,
            "tree maintenance operations executed" : 0
        },
        "async" : {
            "number of allocation state races" : 0,
            "number of operation slots viewed for allocation" : 0,
            "current work queue length" : 0,
            "number of flush calls" : 0,
            "number of times operation allocation failed" : 0,
            "maximum work queue length" : 0,
            "number of times worker found no work" : 0,
            "total allocations" : 0,
            "total compact calls" : 0,
            "total insert calls" : 0,
            "total remove calls" : 0,
            "total search calls" : 0,
            "total update calls" : 0
        },
        "block-manager" : {
            "mapped bytes read" : 0,
            "bytes read" : 446464,
            "bytes written" : 163840,
            "mapped blocks read" : 0,
            "blocks pre-loaded" : 25,
            "blocks read" : 86,
            "blocks written" : 25
        },
        "cache" : {
            "tracked dirty bytes in the cache" : 0,
            "tracked bytes belonging to internal pages in the cache" : 21407,
            "bytes currently in the cache" : 237704,
            "tracked bytes belonging to leaf pages in the cache" : 216297,
            "maximum bytes configured" : 4294967296,
            "tracked bytes belonging to overflow pages in the cache" : 0,
            "bytes read into cache" : 174182,
            "bytes written from cache" : 110151,
            "pages evicted by application threads" : 0,
            "checkpoint blocked page eviction" : 0,
            "unmodified pages evicted" : 0,
            "page split during eviction deepened the tree" : 0,
            "modified pages evicted" : 0,
            "pages selected for eviction unable to be evicted" : 0,
            "pages evicted because they exceeded the in-memory maximum" : 0,
            "pages evicted because they had chains of deleted items" : 0,
            "failed eviction of pages that exceeded the in-memory maximum" : 0,
            "hazard pointer blocked page eviction" : 0,
            "internal pages evicted" : 0,
            "maximum page size at eviction" : 0,
            "eviction server candidate queue empty when topping up" : 0,
            "eviction server candidate queue not empty when topping up" : 0,
            "eviction server evicting pages" : 0,
            "eviction server populating queue, but not evicting pages" : 0,
            "eviction server unable to reach eviction goal" : 0,
            "internal pages split during eviction" : 0,
            "leaf pages split during eviction" : 0,
            "pages walked for eviction" : 0,
            "eviction worker thread evicting pages" : 0,
            "in-memory page splits" : 0,
            "in-memory page passed criteria to be split" : 0,
            "lookaside table insert calls" : 0,
            "lookaside table remove calls" : 0,
            "percentage overhead" : 8,
            "tracked dirty pages in the cache" : 0,
            "pages currently held in the cache" : 47,
            "pages read into cache" : 43,
            "pages read into cache requiring lookaside entries" : 0,
            "pages written from cache" : 13,
            "page written requiring lookaside records" : 0,
            "pages written requiring in-memory restoration" : 0
        },
        "connection" : {
            "pthread mutex condition wait calls" : 6755705,
            "files currently open" : 27,
            "memory allocations" : 2046182,
            "memory frees" : 2044869,
            "memory re-allocations" : 531046,
            "total read I/Os" : 936,
            "pthread mutex shared lock read-lock calls" : 266348,
            "pthread mutex shared lock write-lock calls" : 67963,
            "total write I/Os" : 39
        },
        "cursor" : {
            "cursor create calls" : 70,
            "cursor insert calls" : 25,
            "cursor next calls" : 3113,
            "cursor prev calls" : 2919,
            "cursor remove calls" : 1,
            "cursor reset calls" : 171656,
            "cursor restarted searches" : 0,
            "cursor search calls" : 168752,
            "cursor search near calls" : 2902,
            "truncate calls" : 0,
            "cursor update calls" : 0
        },
        "data-handle" : {
            "connection data handles currently active" : 24,
            "session dhandles swept" : 0,
            "session sweep attempts" : 21,
            "connection sweep dhandles closed" : 0,
            "connection sweep candidate became referenced" : 0,
            "connection sweep dhandles removed from hash list" : 3,
            "connection sweep time-of-death sets" : 22,
            "connection sweeps" : 17279
        },
        "log" : {
            "total log buffer size" : 33554432,
            "log bytes of payload data" : 4111,
            "log bytes written" : 5504,
            "yields waiting for previous log file close" : 0,
            "total size of compressed records" : 3967,
            "total in-memory size of compressed records" : 6785,
            "log records too small to compress" : 6,
            "log records not compressed" : 0,
            "log records compressed" : 5,
            "log flush operations" : 969556,
            "maximum log file size" : 104857600,
            "pre-allocated log files prepared" : 2,
            "number of pre-allocated log files to create" : 2,
            "pre-allocated log files not ready and missed" : 1,
            "pre-allocated log files used" : 0,
            "log release advances write LSN" : 5,
            "records processed by log scan" : 10,
            "log scan records requiring two reads" : 4,
            "log scan operations" : 3,
            "consolidated slot closures" : 2327947,
            "written slots coalesced" : 0,
            "logging bytes consolidated" : 5120,
            "consolidated slot joins" : 11,
            "consolidated slot join races" : 0,
            "busy returns attempting to switch slots" : 0,
            "consolidated slot join transitions" : 2327947,
            "consolidated slot unbuffered writes" : 0,
            "log sync operations" : 7,
            "log sync_dir operations" : 1,
            "log server thread advances write LSN" : 2,
            "log write operations" : 11,
            "log files manually zero-filled" : 0
        },
        "reconciliation" : {
            "pages deleted" : 0,
            "fast-path pages deleted" : 0,
            "page reconciliation calls" : 12,
            "page reconciliation calls for eviction" : 0,
            "split bytes currently awaiting free" : 0,
            "split objects currently awaiting free" : 0
        },
        "session" : {
            "open cursor count" : 20,
            "open session count" : 16
        },
        "thread-yield" : {
            "page acquire busy blocked" : 0,
            "page acquire eviction blocked" : 0,
            "page acquire locked blocked" : 0,
            "page acquire read blocked" : 0,
            "page acquire time sleeping (usecs)" : 0
        },
        "transaction" : {
            "transaction begins" : 11617,
            "transaction checkpoints" : 2900,
            "transaction checkpoint generation" : 2900,
            "transaction checkpoint currently running" : 0,
            "transaction checkpoint max time (msecs)" : 595,
            "transaction checkpoint min time (msecs)" : 3,
            "transaction checkpoint most recent time (msecs)" : 4,
            "transaction checkpoint total time (msecs)" : 12083,
            "transactions committed" : 3,
            "transaction failures due to cache overflow" : 0,
            "transaction range of IDs currently pinned by a checkpoint" : 0,
            "transaction range of IDs currently pinned" : 0,
            "transaction range of IDs currently pinned by named snapshots" : 0,
            "transactions rolled back" : 11614,
            "number of named snapshots created" : 0,
            "number of named snapshots dropped" : 0,
            "transaction sync calls" : 0
        },
        "concurrentTransactions" : {
            "write" : {
                "out" : 0,
                "available" : 128,
                "totalTickets" : 128
            },
            "read" : {
                "out" : 0,
                "available" : 128,
                "totalTickets" : 128
            }
        }
    },
    "writeBacksQueued" : false,
    "mem" : {
        "bits" : 64,
        "resident" : 7,
        "virtual" : 2513,
        "supported" : true,
        "mapped" : 0,
        "mappedWithJournal" : 0
    },
    "metrics" : {
        "commands" : {
            "buildInfo" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(2)
            },
            "getLog" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(2)
            },
            "isMaster" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(10)
            },
            "listCollections" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(1)
            },
            "listDatabases" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(2)
            },
            "replSetGetStatus" : {
                "failed" : NumberLong(2),
                "total" : NumberLong(2)
            },
            "serverStatus" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(1)
            },
            "whatsmyuri" : {
                "failed" : NumberLong(0),
                "total" : NumberLong(2)
            }
        },
        "cursor" : {
            "timedOut" : NumberLong(0),
            "open" : {
                "noTimeout" : NumberLong(0),
                "pinned" : NumberLong(0),
                "total" : NumberLong(0)
            }
        },
        "document" : {
            "deleted" : NumberLong(0),
            "inserted" : NumberLong(0),
            "returned" : NumberLong(0),
            "updated" : NumberLong(0)
        },
        "getLastError" : {
            "wtime" : {
                "num" : 0,
                "totalMillis" : 0
            },
            "wtimeouts" : NumberLong(0)
        },
        "operation" : {
            "fastmod" : NumberLong(0),
            "idhack" : NumberLong(0),
            "scanAndOrder" : NumberLong(0),
            "writeConflicts" : NumberLong(0)
        },
        "queryExecutor" : {
            "scanned" : NumberLong(0),
            "scannedObjects" : NumberLong(0)
        },
        "record" : {
            "moves" : NumberLong(0)
        },
        "repl" : {
            "executor" : {
                "counters" : {
                    "eventCreated" : 0,
                    "eventWait" : 0,
                    "cancels" : 0,
                    "waits" : 0,
                    "scheduledNetCmd" : 0,
                    "scheduledDBWork" : 0,
                    "scheduledXclWork" : 0,
                    "scheduledWorkAt" : 0,
                    "scheduledWork" : 0,
                    "schedulingFailures" : 0
                },
                "queues" : {
                    "networkInProgress" : 0,
                    "dbWorkInProgress" : 0,
                    "exclusiveInProgress" : 0,
                    "sleepers" : 0,
                    "ready" : 0,
                    "free" : 0
                },
                "unsignaledEvents" : 0,
                "eventWaiters" : 0,
                "shuttingDown" : false,
                "networkInterface" : "NetworkInterfaceASIO inShutdown: 0"
            },
            "apply" : {
                "batches" : {
                    "num" : 0,
                    "totalMillis" : 0
                },
                "ops" : NumberLong(0)
            },
            "buffer" : {
                "count" : NumberLong(0),
                "maxSizeBytes" : 268435456,
                "sizeBytes" : NumberLong(0)
            },
            "network" : {
                "bytes" : NumberLong(0),
                "getmores" : {
                    "num" : 0,
                    "totalMillis" : 0
                },
                "ops" : NumberLong(0),
                "readersCreated" : NumberLong(0)
            },
            "preload" : {
                "docs" : {
                    "num" : 0,
                    "totalMillis" : 0
                },
                "indexes" : {
                    "num" : 0,
                    "totalMillis" : 0
                }
            }
        },
        "storage" : {
            "freelist" : {
                "search" : {
                    "bucketExhausted" : NumberLong(0),
                    "requests" : NumberLong(0),
                    "scanned" : NumberLong(0)
                }
            }
        },
        "ttl" : {
            "deletedDocuments" : NumberLong(0),
            "passes" : NumberLong(2901)
        }
    },
    "ok" : 1
}

``

看看有哪些库

show dbs; admin 0.000GB local 0.000GB restfiddle 0.001GB

#use命令

MongoDB 用 

use + 数据库名称

的方式来创建数据库。use 会创建一个新的数据库,如果该数据库存在,则返回这个数据库。」



例子1. 創建 root 用戶名密碼

####Step1.首先,切换到admin db (schema):

use admin; switched to db admin

####Step2.在該 schema 下面設置用戶名,密碼:

db.createUser({ user: "root",pwd: "root",customData:{name:"root"},roles:[{ role: "userAdminAnyDatabase",db: "admin" }]}) Successfully added user: { "user" : "root", "customData" : { "name" : "root" }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] } db.auth('root','root') 1

####Step3.给restfiddle库权限

var r = { "_id": "restfiddle.root", "user": "root", "db": "restfiddle", "credentials": { "SCRAM-SHA-1": { "iterationCount": 10000, "salt": "riZjwBYHvkcV99typ8BRMA==", "storedKey": "E2QOruLrBNXD1mlQTX0TQogL/ws=", "serverKey": "JEQhfa/5x7+aNzKrFvKRkctXXfQ=" } }, "roles": [ { "role": "dbOwner", "db": "restfiddle" }, { "role": "read", "db": "restfiddle" }, { "role": "readWrite", "db": "restfiddle" } ] }

db.system.users.insert(r)

#[Database Operations](https://docs.mongodb.com/manual/reference/command/?spm=5176.100239.blogcont68925.15.OLu8c1#database-operations)


#查看数据库的文档(json document),集合(collection)结构

我们切换到库use restfiddle,看一下当前库的状态:

use restfiddle; switched to db restfiddle db.stats() { "db" : "restfiddle", "collections" : 14, "objects" : 298, "avgObjSize" : 362.18120805369125, "dataSize" : 107930, "storageSize" : 372736, "numExtents" : 0, "indexes" : 15, "indexSize" : 339968, "ok" : 1 }

查看库restfiddle有哪些集合:

db restfiddle show collections; EntityAuth activityLog baseNode

config conversation httpRequestHeader oAuth2 project rfRequest rfResponse runnerLog tag user workspace

查看user集合里面有哪些json document:

db.user.find(); { "_id" : ObjectId("575fa8a2ba637304fffbad5e"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$JzistJ7qIP80KMYwSqSu7uShUGn4bg/m.u0/51HcKHVIui/URgbTi", "email" : "rf@example.com", "name" : "RF Admin", "status" : "ACTIVE", "version" : NumberLong(0) } { "_id" : ObjectId("575fa8a2ba637304fffbad5f"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$eyrBDJyNepEPsX3qTUveqeKNxYFq/nQq4sTixY/nRZhFynTW9izxm", "email" : "anuja@example.com", "name" : "Anuja Kumar", "status" : "ACTIVE", "version" : NumberLong(0) } db.user.find().pretty(); { "_id" : ObjectId("575fa8a2ba637304fffbad5e"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$JzistJ7qIP80KMYwSqSu7uShUGn4bg/m.u0/51HcKHVIui/URgbTi", "email" : "rf@example.com", "name" : "RF Admin", "status" : "ACTIVE", "version" : NumberLong(0) } { "_id" : ObjectId("575fa8a2ba637304fffbad5f"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$eyrBDJyNepEPsX3qTUveqeKNxYFq/nQq4sTixY/nRZhFynTW9izxm", "email" : "anuja@example.com", "name" : "Anuja Kumar", "status" : "ACTIVE", "version" : NumberLong(0) }

我们看到,json的pretty()函数使得输出更好阅读。

#主键_id唯一性

我们往user集里面插入一条记录:

var newUser = { ... "_id" : ObjectId("575fa8a2ba637304fffbad5e"), ... "_class" : "com.restfiddle.entity.User", ... "password" : "$2a$10$JzistJ7qIP80KMYwSqSu7uShUGn4bg/m.u0/51HcKHVIui/URgbTi", ... "email" : "rf@example.com", ... "name" : "RF Admin", ... "status" : "ACTIVE", ... "version" : NumberLong(0) ... }

db.user.insert(newUser) WriteResult({ "nInserted" : 0,

"writeError" : {
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: restfiddle.user index: _id_ dup key: { : ObjectId('575fa8a2ba637304fffbad5e') }"
}

})

看到了,提示我们:

> "E11000 duplicate key error collection: restfiddle.user index: _id_ dup key: { : ObjectId('575fa8a2ba637304fffbad5e') }"

这个提示,告诉我们,在mongoDB中,集合里面的文档json的主键_id是唯一的。



#插入一条json

db.user.find(); { "_id" : ObjectId("575fa8a2ba637304fffbad5e"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$JzistJ7qIP80KMYwSqSu7uShUGn4bg/m.u0/51HcKHVIui/URgbTi", "email" : "rf@example.com", "name" : "RF Admin", "status" : "ACTIVE", "version" : NumberLong(0) } { "_id" : ObjectId("575fa8a2ba637304fffbad5f"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$eyrBDJyNepEPsX3qTUveqeKNxYFq/nQq4sTixY/nRZhFynTW9izxm", "email" : "anuja@example.com", "name" : "Anuja Kumar", "status" : "ACTIVE", "version" : NumberLong(0) }

db.user.insert({'name':'Jason Chen','status':'ACTIVE'})

db.user.find().pretty(); { "_id" : ObjectId("575fa8a2ba637304fffbad5e"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$JzistJ7qIP80KMYwSqSu7uShUGn4bg/m.u0/51HcKHVIui/URgbTi", "email" : "rf@example.com", "name" : "RF Admin", "status" : "ACTIVE", "version" : NumberLong(0) } { "_id" : ObjectId("575fa8a2ba637304fffbad5f"), "_class" : "com.restfiddle.entity.User", "password" : "$2a$10$eyrBDJyNepEPsX3qTUveqeKNxYFq/nQq4sTixY/nRZhFynTW9izxm", "email" : "anuja@example.com", "name" : "Anuja Kumar", "status" : "ACTIVE", "version" : NumberLong(0) } { "_id" : ObjectId("58cfeededc2042106f53c868"), "name" : "Jason Chen", "status" : "ACTIVE" }

我们可以看出,主键_id是每次插入的时候,自动生成的。那么,生成的算法是怎样的呢?

var id=new ObjectId(); id ObjectId("58cfefcddc2042106f53c869")

参考:[MongoDB ObjectId详解及使用](http://www.jianshu.com/p/dd63b93a5955)

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏hbbliyong

基于Three.js的360度全景--photo-sphere-viewer--简介

这个是基于three.js的全景插件  photo-sphere-viewer.js  ————————————————————————————————————...

5989
来自专栏糊一笑

移动端效果之Swiper

写在前面 最近在做移动端方面运用到了饿了么的vue前端组件库,因为不想单纯用组件而使用它,故想深入了解一下实现原理。后续将会继续研究一下其他的组件实现原理,有兴...

3218
来自专栏糊一笑

移动端效果之IndexList

写在前面 接着前面的移动端效果讲,这次讲解的的是IndexList的实现原理。效果如下: ? 代码请看这里:github 移动端效果之swiper 移动端效果之...

2254
来自专栏Charlie's Road

图层几何学 -- iOS Core Animation 系列二

《图层树和寄宿图 -- iOS Core Animation 系列一》介绍了图层的基础知识和一些属性方法。这篇主要内容是学习下图层在父图层上怎么控制位置和尺寸的...

963
来自专栏python爬虫日记

wxpython 窗口排版- proportion/flag/border参数说明

新学习wxpython,一直纠结于窗口控件的排版,经过几天的查资料、试验,总结如下。

2153
来自专栏mukekeheart的iOS之旅

iOS学习——Quartz2D学习之UIKit绘制

  在IOS中绘图技术主要包括:UIKit、Quartz 2D、Core Animation和OpenGL ES。其中Core Animation提供动画实现技...

1212
来自专栏向治洪

React Native之Picker组件详解

Picker简介 在iOS和Android中选择器(Picker)是常见的控件之一,比如TimePickr(Android),pickerView(ios),并...

5436
来自专栏GuZhenYin

C#使用Xamarin开发可移植移动应用(3.Xamarin.Views控件)附源码

前言 源码地址:https://github.com/l2999019/DemoApp 可以Star一下,随意 - - 说点什么.. .NET core2.0 ...

2389
来自专栏从零开始学自动化测试

appium+python自动化58-xpath定位

3.class属性唯一的话,可以通过class属性定位到,定位class属性有两种方法

2385
来自专栏zcqshine's blog

ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示

3684

扫码关注云+社区

领取腾讯云代金券