首页 > 编程学习 > NoSQL - MongoDB 常见的shell操作 - 安装

NoSQL - MongoDB 常见的shell操作 - 安装

发布时间:2022/11/9 0:49:10

1.应用场景

主要用于使用客户端工具进行快速地测试mongodb使用。  

2.学习/操作

1.文档阅读

MongoDB 创建数据库 | 菜鸟教程 -- 跟着菜鸟走一遍就算入门了

2.整理输出

环境

Using MongoDB: 6.0.2

Using Mongosh: 1.6.0

本篇文章不是API手册,所有这里对Shell的使用,也是基础的介绍,什么功能可以用什么语句.

主要是为了展示使用MongoDB Shell的方便性,如果需要知道具体的MongoDB Shell语法可以查阅官方文档。

基本管理语法

// 查询所有数据库

show dbs

Note:

如果数据库中没有数据,是不会显示在结果中的

默认,会进入到test数据库中,但是因为test中没有数据,所以并不会显示「不论是在cli还是gui客户端中」

// 查看当前数据库

db

// 使用/切换到某个数据库

use db-name

// 显示所有表
show collections

 
// 显示数据库状态信息

db.stats()

// 显示集合表状态信息
db.numbers.stats()

// 停止数据库
db.shutdownServer()

// 获取数据库操作命令
db.help()

// 获取表操作命令
db.foo.help()

// 能自动帮我们补全命令
tab 键

上面的操作结果如下:

test> show dbs

admin   100.00 KiB

config  120.00 KiB

local    72.00 KiB

test> db

test

test> show collections

test> db.createCollection("william")

{ ok: 1 }

test> show dbs

admin   100.00 KiB

config  132.00 KiB

local    72.00 KiB

test      8.00 KiB

test> show collections

william

test> db.stats()

{

  db: 'test',

  collections: 1,

  views: 0,

  objects: 0,

  avgObjSize: 0,

  dataSize: 0,

  storageSize: 4096,

  indexes: 1,

  indexSize: 4096,

  totalSize: 8192,

  scaleFactor: 1,

  fsUsedSize: 154879320064,

  fsTotalSize: 494384795648,

  ok: 1

}

test> db.numbers.stats()

{

  ns: 'test.numbers',

  size: 0,

  count: 0,

  numOrphanDocs: 0,

  storageSize: 0,

  totalSize: 0,

  nindexes: 0,

  totalIndexSize: 0,

  indexSizes: {},

  scaleFactor: 1,

  ok: 1

}

test> db.help()

  Database Class:

    getMongo                                   Returns the current database connection

    getName                                    Returns the name of the DB

    getCollectionNames                         Returns an array containing the names of all collections in the current database.

    getCollectionInfos                         Returns an array of documents with collection information, i.e. collection name and options, for the current database.

    runCommand                                 Runs an arbitrary command on the database.

    adminCommand                               Runs an arbitrary command against the admin database.

    aggregate                                  Runs a specified admin/diagnostic pipeline which does not require an underlying collection.

    getSiblingDB                               Returns another database without modifying the db variable in the shell environment.

    getCollection                              Returns a collection or a view object that is functionally equivalent to using the db.<collectionName>.

    dropDatabase                               Removes the current database, deleting the associated data files.

    createUser                                 Creates a new user for the database on which the method is run. db.createUser() returns a duplicate user error if the user already exists on the database.

    updateUser                                 Updates the user’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values. This includes updates to the user’s roles array.

    changeUserPassword                         Updates a user’s password. Run the method in the database where the user is defined, i.e. the database you created the user.

    logout                                     Ends the current authentication session. This function has no effect if the current session is not authenticated.

    dropUser                                   Removes the user from the current database.

    dropAllUsers                               Removes all users from the current database.

    auth                                       Allows a user to authenticate to the database from within the shell.

    grantRolesToUser                           Grants additional roles to a user.

    revokeRolesFromUser                        Removes a one or more roles from a user on the current database.

    getUser                                    Returns user information for a specified user. Run this method on the user’s database. The user must exist on the database on which the method runs.

    getUsers                                   Returns information for all the users in the database.

    createCollection                           Create new collection

    createView                                 Create new view

    createRole                                 Creates a new role.

    updateRole                                 Updates the role’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values.

    dropRole                                   Removes the role from the current database.

    dropAllRoles                               Removes all roles from the current database.

    grantRolesToRole                           Grants additional roles to a role.

    revokeRolesFromRole                        Removes a one or more roles from a role on the current database.

    grantPrivilegesToRole                      Grants additional privileges to a role.

    revokePrivilegesFromRole                   Removes a one or more privileges from a role on the current database.

    getRole                                    Returns role information for a specified role. Run this method on the role’s database. The role must exist on the database on which the method runs.

    getRoles                                   Returns information for all the roles in the database.

    currentOp                                  Calls the currentOp command. Returns a document that contains information on in-progress operations for the database instance. The db.currentOp() method wraps the database command currentOp.

    killOp                                     Calls the killOp command. Terminates an operation as specified by the operation ID. To find operations and their corresponding IDs, see $currentOp or db.currentOp().

    shutdownServer                             Calls the shutdown command. Shuts down the current mongod or mongos process cleanly and safely. You must issue the db.shutdownServer() operation against the admin database.

    fsyncLock                                  Calls the fsync command. Forces the mongod to flush all pending write operations to disk and locks the entire mongod instance to prevent additional writes until the user releases the lock with a corresponding db.fsyncUnlock() command.

    fsyncUnlock                                Calls the fsyncUnlock command. Reduces the lock taken by db.fsyncLock() on a mongod instance by 1.

    version                                    returns the db version. uses the buildinfo command

    serverBits                                 returns the db serverBits. uses the buildInfo command

    isMaster                                   Calls the isMaster command

    hello                                      Calls the hello command

    serverBuildInfo                            returns the db serverBuildInfo. uses the buildInfo command

    serverStatus                               returns the server stats. uses the serverStatus command

    stats                                      returns the db stats. uses the dbStats command

    hostInfo                                   Calls the hostInfo command

    serverCmdLineOpts                          returns the db serverCmdLineOpts. uses the getCmdLineOpts command

    rotateCertificates                         Calls the rotateCertificates command

    printCollectionStats                       Prints the collection.stats for each collection in the db.

    getFreeMonitoringStatus                    Calls the getFreeMonitoringStatus command

    disableFreeMonitoring                      returns the db disableFreeMonitoring. uses the setFreeMonitoring command

    enableFreeMonitoring                       returns the db enableFreeMonitoring. uses the setFreeMonitoring command

    getProfilingStatus                         returns the db getProfilingStatus. uses the profile command

    setProfilingLevel                          returns the db setProfilingLevel. uses the profile command

    setLogLevel                                returns the db setLogLevel. uses the setParameter command

    getLogComponents                           returns the db getLogComponents. uses the getParameter command

    cloneDatabase                              deprecated, non-functional

    cloneCollection                            deprecated, non-functional

    copyDatabase                               deprecated, non-functional

    commandHelp                                returns the db commandHelp. uses the passed in command with help: true

    listCommands                               Calls the listCommands command

    getLastErrorObj                            Calls the getLastError command

    getLastError                               Calls the getLastError command

    printShardingStatus                        Calls sh.status(verbose)

    printSecondaryReplicationInfo              Prints secondary replicaset information

    getReplicationInfo                         Returns replication information

    printReplicationInfo                       Formats sh.getReplicationInfo

    printSlaveReplicationInfo                  DEPRECATED. Use db.printSecondaryReplicationInfo

    setSecondaryOk                             This method is deprecated. Use db.getMongo().setReadPref() instead

    watch                                      Opens a change stream cursor on the database

    sql                                        (Experimental) Runs a SQL query against Atlas Data Lake. Note: this is an experimental feature that may be subject to change in future releases.

test> db.william.help()

  Collection Class:

    aggregate                                  Calculates aggregate values for the data in a collection or a view.

    bulkWrite                                  Performs multiple write operations with controls for order of execution.

    count                                      Returns the count of documents that would match a find() query for the collection or view.

    countDocuments                             Returns the count of documents that match the query for a collection or view.

    deleteMany                                 Removes all documents that match the filter from a collection.

    deleteOne                                  Removes a single document from a collection.

    distinct                                   Finds the distinct values for a specified field across a single collection or view and returns the results in an array.

    estimatedDocumentCount                     Returns the count of all documents in a collection or view.

    find                                       Selects documents in a collection or view.

    findAndModify                              Modifies and returns a single document.

    findOne                                    Selects documents in a collection or view.

    renameCollection                           Renames a collection.

    findOneAndDelete                           Deletes a single document based on the filter and sort criteria, returning the deleted document.

    findOneAndReplace                          Modifies and replaces a single document based on the filter and sort criteria.

    findOneAndUpdate                           Updates a single document based on the filter and sort criteria.

    insert                                     Inserts a document or documents into a collection.

    insertMany                                 Inserts multiple documents into a collection.

    insertOne                                  Inserts a document into a collection.

    isCapped                                   Checks if a collection is capped

    remove                                     Removes documents from a collection.

    replaceOne                                 Replaces a single document within the collection based on the filter.

    update                                     Modifies an existing document or documents in a collection.

    updateMany                                 Updates all documents that match the specified filter for a collection.

    updateOne                                  Updates a single document within the collection based on the filter.

    compactStructuredEncryptionData            Compacts structured encryption data

    convertToCapped                            calls {convertToCapped:'coll', size:maxBytes}} command

    createIndexes                              Creates one or more indexes on a collection

    createIndex                                Creates one index on a collection

    ensureIndex                                Creates one index on a collection

    getIndexes                                 Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.

    getIndexSpecs                              Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.

    getIndices                                 Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.

    getIndexKeys                               Return an array of key patterns for indexes defined on collection

    dropIndexes                                Drops the specified index or indexes (except the index on the _id field) from a collection.

    dropIndex                                  Drops or removes the specified index from a collection.

    totalIndexSize                             Reports the total size used by the indexes on a collection.

    reIndex                                    Rebuilds all existing indexes on a collection.

    getDB                                      Get current database.

    getMongo                                   Returns the Mongo object.

    dataSize                                   This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.

    storageSize                                The total amount of storage allocated to this collection for document storage.

    totalSize                                  The total size in bytes of the data in the collection plus the size of every index on the collection.

    drop                                       Removes a collection or view from the database.

    exists                                     Returns collection infos if the collection exists or null otherwise.

    getFullName                                Returns the name of the collection prefixed with the database name.

    getName                                    Returns the name of the collection.

    runCommand                                 Runs a db command with the given name where the first param is the collection name.

    explain                                    Returns information on the query plan.

    stats                                      Returns statistics about the collection.

    latencyStats                               returns the $latencyStats aggregation for the collection. Takes an options document with an optional boolean 'histograms' field.

    initializeOrderedBulkOp                    Initializes an ordered bulk command. Returns an instance of Bulk

    initializeUnorderedBulkOp                  Initializes an unordered bulk command. Returns an instance of Bulk

    getPlanCache                               Returns an interface to access the query plan cache for a collection. The interface provides methods to view and clear the query plan cache.

    mapReduce                                  Calls the mapReduce command

    validate                                   Calls the validate command. Default full value is false

    getShardVersion                            Calls the getShardVersion command

    getShardDistribution                       Prints the data distribution statistics for a sharded collection.

    watch                                      Opens a change stream cursor on the collection

    hideIndex                                  Hides an existing index from the query planner.

    unhideIndex                                Unhides an existing index from the query planner.

test>

开始基于某个数据库进行操作。

1、切换数据库

use test

创建数据库并不是必须的操作,数据库与集合只有在第一次插入文档时才会被创建,与对数据的动态处理方式是一致的。

简化并加速开发过程,而且有利于动态分配命名空间。

如果担心数据库或集合被意外创建,可以开启严格模式

2、插入语法

db.users.insert({username:"smith"}) ❌ // 被摒弃,但是依然可以使用,不过推荐使用insertOne

db.users.insertOne({username:"smith"})。✅


db.users.save({username:"smith"}) // 新版本下出现报错,而且从帮助命令中并没有找到,应该是被摒弃

3、查找语法

db.users.find()


db.users.count() // DeprecationWarning: Collection.count() is deprecated. Use countDocuments or estimatedDocumentCount.

推荐

test> db.users.countDocuments()

3

test> db.users.estimatedDocumentCount()

3

test>

4、更新语法

// 把用户名为smith的用户的国家改成Canada

db.users.updateOne({username:"smith"},{$set:{country:"Canada"}})

// 把用户名为smith的用户的国家字段给移除

db.users.updateOne({username:"smith"},{$unset:{country:1}})


// 这里主要体现多值修改,在favorties字段中添加多个值

db.users.updateOne({username:"jones"},{$set:{favorites:{movies:["casablance","rocky"]}}})

...

5、删除语法

db.users.remove() // 删除所有数据

DeprecationWarning: Collection.remove() is deprecated. Use deleteOne, deleteMany, findOneAndDelete, or bulkWrite.

MongoshInvalidInputError: [COMMON-10001] Missing required argument at position 0 (Collection.remove)

db.users.drop()

db.foo.deleteOne({favorties.cities:"cheyene"}) // 根据条件进行删除


db.dropDatabase() // 删除整个集合

6、索引相关语法

// 创建一个升序索引

db.numbers.ensureIndex({num:1})

// 获取全部索引

db.numbers.getIndexes()

以上的命令只是简单实例。

更多命令请参见官方文档或者中文网文档,然后实践确认

参考_MonogDB 中文网

假设如果你之前没有学习过任何数据库语法,同时开始学SQL查询语法和MongoDB 查询语法,你会发现哪一个更简单呢?

某网友的回答:如果你使用的是Java驱动去操作MongoDB,你会发现任何的查询都像Hibernate提供出来的查询方式一样,只要构建好一个查询条件对象,便能轻松查询(接下来会给出示例),博主之前熟悉ES6,所以入手MongoDB JS Shell完成没问题,也正因为这样简洁,完善的查询机制,深深的爱上了MongoDB。

个人回答:单从使用的语法上来说,mongodb明显简单很多。 

不过从功能上分析,二者代表了两种不同类型的DB,各有使用场景,应该合理利用,解决实际问题。

后续补充

...

3.问题/补充

TBD

4.参考

参见上面文档列表

后续补充

...

Copyright © 2010-2022 dgrt.cn 版权所有 |关于我们| 联系方式