Thursday, September 24, 2020

mongodump, mongorestore

 mongodump --uri="mongodb://localhost:27017/database" //sẽ lưu dữ liệu từ mongodb vào thư mục dump

mongorestore  dump/
//sẽ lấy dữ liệu từ thư mục dump và insert vào mongodb://localhost:27017


Tuesday, February 4, 2020

Xác thực trong mongodb

Từ code:
muốn truy cập vào mongodb có pass thì phải tạo account từ database muốn truy cập vào
ví dụ
"accountDS": {
    "name": "accountDS",
    "connector": "mongodb",
    "host": "demo.strongloop.com",
    "port": 27017,
    "database": "demoDB",
    "username": "demoUser",
    "password": "L00pBack"
  }
thi tức là loopback muốn truy cập vào database tên là demoDB
vậy thì phải tạo user sau trên mongodb

//_id là demoDB.demoUser
use demoDB;
db.createUser({user:"demoUser",pwd:"L00pBack",roles:["readWrite","dbAdmin"]})

chứ không đuợc tạo user trên database admin như sau

//_id là admin.demoUser
use admin;
db.createUser({user:"demoUser",pwd:"L00pBack",roles:["readWrite","dbAdmin"]})

(tuy 2 user có cùng tên là demoUser nhưng vì đuợc tạo trên 2 database khác nhau nên chúng tồn tại song song đuợc)

-----------
Từ client
Tuy nhiên, khi sử dụng mongo compass để truy cập vào DB thì lại phải tạo user trên database admin
(ví dụ: với 2 user đã tạo ở trên thì admin.demoUser mới có thể sử dụng trong mongo compass đuợc. demoDB.demoUser không thể dùng trong compass đuợc)_

Sunday, January 5, 2020

Enable Access Control

Overview

Enabling access control on a MongoDB deployment enforces authentication, requiring users to identify themselves. When accessing a MongoDB deployment that has access control enabled, users can only perform actions as determined by their roles.
The following tutorial enables access control on a standalone mongod instance and uses the default authentication mechanism. For all supported authentication mechanisms, see Authentication Mechanisms.

User Administrator

With access control enabled, ensure you have a user with userAdmin or userAdminAnyDatabase role in the admin database. This user can administrate user and roles such as: create users, grant or revoke roles from users, and create or modify customs roles.

Procedure

The following procedure first adds a user administrator to a MongoDB instance running without access control and then enables access control.
NOTE
The example MongoDB instance uses port 27017 and the data directory /var/lib/mongodb directory . The example assumes the existence of the data directory /var/lib/mongodb. Specify a different data directory as appropriate.
1

Start MongoDB without access control.

Start a standalone mongod instance without access control.
For example, open a terminal and issue the following:
mongod --port 27017 --dbpath /var/lib/mongodb
2

Connect to the instance.

For example, open a new terminal and connect a mongo shell to the instance:
mongo --port 27017
Specify additional command line options as appropriate to connect the mongo shell to your deployment, such as --host.
3

Create the user administrator.

From the mongo shell, add a user with the userAdminAnyDatabase role in the admin database. Include additional roles as needed for this user. For example, the following creates the user myUserAdmin in the admin database with the userAdminAnyDatabase role and the readWriteAnyDatabase role.
TIP
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
NOTE
The database where you create the user (in this example, admin) is the user’s authentication database. Although the user would authenticate to this database, the user can have roles in other databases; i.e. the user’s authentication database does not limit the user’s privileges.
4

Re-start the MongoDB instance with access control.

  1. Shut down the mongod instance. For example, from the mongo shell, issue the following command:
    db.adminCommand( { shutdown: 1 } )
    
  2. Exit the mongo shell.
  3. From the terminal, re-start the mongod instance with the --auth command line option or, if using a configuration file, the security.authorization setting.
mongod --auth --port 27017 --dbpath /var/lib/mongodb
Clients that connect to this instance must now authenticate themselves as a MongoDB user. Clients can only perform actions as determined by their assigned roles.
5

Connect and authenticate as the user administrator.

Using the mongo shell, you can:
  • Connect with authentication by passing in user credentials, or
  • Connect first without authentication, and then issue the db.auth() method to authenticate.
Start a mongo shell with the -u <username>-p, and the --authenticationDatabase <database> command line options:
mongo --port 27017  --authenticationDatabase "admin" -u "myUserAdmin" -p
Enter your password when prompted.
6

Create additional users as needed for your deployment.

Once authenticated as the user administrator, use db.createUser() to create additional users. You can assign any built-in roles or user-defined roles to the users.
The following operation adds a user myTester to the test database who has readWrite role in the test database as well as read role in the reporting database.
TIP
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.
use test
db.createUser(
  {
    user: "myTester",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)
NOTE
The database where you create the user (in this example, test) is that user’s authentication database. Although the user would authenticate to this database, the user can have roles in other databases; i.e. the user’s authentication database does not limit the user’s privileges.
After creating the additional users, disconnect the mongo shell.
7

Connect to the instance and authenticate as myTester.

After disconnecting the mongo shell as myUserAdmin, reconnect as myTester. You can:
  • Connect with authentication by passing in user credentials, or
  • Connect first withouth authentication, and then issue the db.auth() method to authenticate.
Start a mongo shell with the -u <username>-p, and the --authenticationDatabase <database> command line options:
mongo --port 27017 -u "myTester" --authenticationDatabase "test" -p
Enter the password for the user when prompted.
8

Insert a document as myTester.

As myTester, you have privileges to perform read and write operations in the test database (as well as perform read operations in the reporting database). Once authenticated as myTester, insert a document into a collection in test database. For example, you can perform the following insert operation in the test database:
db.foo.insert( { x: 1, y: 1 } )

Thursday, January 2, 2020

mongo Shell Quick Reference



mongo Shell Command History

You can retrieve previous commands issued in the mongo shell with the up and down arrow keys. Command history is stored in ~/.dbshell file. See .dbshell for more information.

Command Line Options

The mongo shell can be started with numerous options. See mongo shell page for details on all available options.
The following table displays some common options for mongo:
OptionDescription
--helpShow command line options
--nodb
Start mongo shell without connecting to a database.
To connect later, see Opening New Connections.
--shell
Used in conjunction with a JavaScript file (i.e. <file.js>) to continue in the mongo shell after running the JavaScript file.
See JavaScript file for an example.

Command Helpers

The mongo shell provides various help. The following table displays some common help methods and commands:
Help Methods and CommandsDescription
helpShow help.
db.help()Show help for database methods.
db.<collection>.help()Show help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection.
show dbs
Print a list of all databases on the server.
The operation corresponds to the listDatabases command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.
use <db>Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections
Print a list of all collections for current database.
SEE ALSO
show usersPrint a list of users for current database.
show rolesPrint a list of all roles, both user-defined and built-in, for the current database.
show profilePrint the five most recent operations that took 1 millisecond or more. See documentation on the database profiler for more information.
show databases
Print a list of all available databases.
The operation corresponds to the listDatabases command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.
load()Execute a JavaScript file. See Write Scripts for the mongo Shell for more information.

Basic Shell JavaScript Operations

The mongo shell provides a JavaScript API for database operations.
In the mongo shell, db is the variable that references the current database. The variable is automatically set to the default database test or is set when you use the use <db> to switch current database.
The following table displays some common JavaScript operations:
JavaScript Database OperationsDescription
db.auth()If running in secure mode, authenticate the user.
coll = db.<collection>
Set a specific collection in the current database to a variable coll, as in the following example:
coll = db.myCollection;
You can perform operations on the myCollection using the variable, as in the following example:
coll.find();
db.collection.find()
Find all documents in the collection and returns a cursor.
See the db.collection.find() and Query Documents for more information and examples.
See Iterate a Cursor in the mongo Shell for information on cursor handling in the mongo shell.
db.collection.insertOne()Insert a new document into the collection.
db.collection.insertMany()Insert multiple new documents into the collection.
db.collection.updateOne()Update a single existing document in the collection.
db.collection.updateMany()Update multiple existing documents in the collection.
db.collection.save()Insert either a new document or update an existing document in the collection.
db.collection.deleteOne()Delete a single document from the collection.
db.collection.deleteMany()Delete documents from the collection.
db.collection.drop()Drops or removes completely the collection.
db.collection.createIndex()Create a new index on the collection if the index does not exist; otherwise, the operation has no effect.
db.getSiblingDB()Return a reference to another database using this same connection without explicitly switching the current database. This allows for cross database queries.
For more information on performing operations in the shell, see:

Keyboard Shortcuts

The mongo shell provides most keyboard shortcuts similar to those found in the bash shell or in Emacs. For some functions mongo provides multiple key bindings, to accommodate several familiar paradigms.
The following table enumerates the keystrokes supported by the mongo shell:
KeystrokeFunction
Up-arrowprevious-history
Down-arrownext-history
Homebeginning-of-line
Endend-of-line
Tabautocomplete
Left-arrowbackward-character
Right-arrowforward-character
Ctrl-left-arrowbackward-word
Ctrl-right-arrowforward-word
Meta-left-arrowbackward-word
Meta-right-arrowforward-word
Ctrl-Abeginning-of-line
Ctrl-Bbackward-char
Ctrl-Cexit-shell
Ctrl-Ddelete-char (or exit shell)
Ctrl-Eend-of-line
Ctrl-Fforward-char
Ctrl-Gabort
Ctrl-Jaccept-line
Ctrl-Kkill-line
Ctrl-Lclear-screen
Ctrl-Maccept-line
Ctrl-Nnext-history
Ctrl-Pprevious-history
Ctrl-Rreverse-search-history
Ctrl-Sforward-search-history
Ctrl-Ttranspose-chars
Ctrl-Uunix-line-discard
Ctrl-Wunix-word-rubout
Ctrl-Yyank
Ctrl-ZSuspend (job control works in linux)
Ctrl-H (i.e. Backspace)backward-delete-char
Ctrl-I (i.e. Tab)complete
Meta-Bbackward-word
Meta-Ccapitalize-word
Meta-Dkill-word
Meta-Fforward-word
Meta-Ldowncase-word
Meta-Uupcase-word
Meta-Yyank-pop
Meta-[Backspace]backward-kill-word
Meta-<beginning-of-history
Meta->end-of-history

Queries

In the mongo shell, perform read operations using the find() and findOne() methods.
The find() method returns a cursor object which the mongo shell iterates to print documents on screen. By default, mongo prints the first 20. The mongo shell will prompt the user to “Type it” to continue iterating the next 20 results.
The following table provides some common read operations in the mongo shell:
Read OperationsDescription
db.collection.find(<query>)
Find the documents matching the <query> criteria in the collection. If the <query> criteria is not specified or is empty (i.e {} ), the read operation selects all documents in the collection.
The following example selects the documents in the users collection with the name field equal to "Joe":
coll = db.users;
coll.find( { name: "Joe" } );
For more information on specifying the <query> criteria, see Specify Equality Condition.
db.collection.find(<query>, <projection>)
Find documents matching the <query> criteria and return just specific fields in the <projection>.
The following example selects all documents from the collection but returns only the name field and the _id field. The _id is always returned unless explicitly specified to not return.
coll = db.users;
coll.find( { }, { name: true } );
For more information on specifying the <projection>, see Project Fields to Return from Query.
db.collection.find().sort(<sort order>)
Return results in the specified <sort order>.
The following example selects all documents from the collection and returns the results sorted by the name field in ascending order (1). Use -1 for descending order:
coll = db.users;
coll.find().sort( { name: 1 } );
db.collection.find(<query>).sort(<sort order>)Return the documents matching the <query> criteria in the specified <sort order>.
db.collection.find( ... ).limit( <n> )Limit result to <n> rows. Highly recommended if you need only a certain number of rows for best performance.
db.collection.find( ... ).skip( <n> )Skip <n> results.
db.collection.count()Returns total number of documents in the collection.
db.collection.find(<query>).count()
Returns the total number of documents that match the query.
The count() ignores limit() and skip(). For example, if 100 records match but the limit is 10, count() will return 100. This will be faster than iterating yourself, but still take time.
db.collection.findOne(<query>)
Find and return a single document. Returns null if not found.
The following example selects a single document in the users collection with the name field matches to "Joe":
coll = db.users;
coll.findOne( { name: "Joe" } );
Internally, the findOne() method is the find() method with a limit(1).
See Query Documents documentation for more information and examples. See Query and Projection Operators to specify other query operators.

Error Checking Methods

The mongo shell write method integrates the Write Concern directly into the method execution, and returns a WriteResult() object that contains the results of the operation, including any write errors and write concern errors.

Administrative Command Helpers

The following table lists some common methods to support database administration:
JavaScript Database Administration MethodsDescription
db.fromColl.renameCollection(<toColl>)Rename collection from fromColl to <toColl>. See Naming Restrictions.
db.getCollectionNames()Get the list of all collections in the current database.
db.dropDatabase()Drops the current database.
See also administrative database methods for a full list of methods.

Opening Additional Connections

You can create new connections within the mongo shell.
The following table displays the methods to create the connections:
JavaScript Connection Create MethodsDescription
db = connect("<host><:port>/<dbname>")
Open a new database connection.
conn = new Mongo()
db = conn.getDB("dbname")
Open a connection to a new server using new Mongo().
Use getDB() method of the connection to select a database.
See also Opening New Connections for more information on the opening new connections from the mongo shell.

Miscellaneous

The following table displays some miscellaneous methods:
MethodDescription
Object.bsonsize(<document>)Prints the BSON size of a <document> in bytes

Additional Resources

Consider the following reference material that addresses the mongo shell and its interface:
Additionally, the MongoDB source code repository includes a jstests directory which contains numerous mongo shell scripts.