MongoDB Simple to use

Source: Internet
Author: User
Tags auth create index createindex mongodb find mongodb update

MongoDB The database defaults to no user name and password, that is, no access restrictions. To facilitate database management and security, database users need to be created.

User-created syntax format

 {user:   "  <name>   " ,  pwd : "  <cleartext password   " ,customdata: { <any Information>},roles: [{role:   " <ROLE>   ", DB:  " <DATABASE>  } |  " <ROLE>   " ,]}  
    • User field: Name of the person; must fill in
    • PWD field: User's password; must fill in
    • Cusomdata field: For any content, for example, can be introduced to the user's full name;
    • Roles field: Specify the user's role, you can use an empty array to set the null role for the new user; must fill in
    • The Roles field allows you to specify built-in roles and user-defined roles. must fill in
 #常用角色说明见官方文档

https://docs.mongodb.com/manual/reference/built-in-roles/

Permissions role

Floating red for a common role

Read
ReadWrite
dbAdmin: Allows the user to perform administrative functions in the specified database, such as index creation, deletion, viewing statistics, or accessing System.profile
useradmin: Allows the user to write to the System.users collection to create, delete, and manage users in the specified database

Readanydatabase: Only available in the Admin database, giving users read access to all databases
Readwriteanydatabase: Only available in the Admin database, giving users read and write access to all databases
Useradminanydatabase: Only available in the Admin database, giving the user useradmin permissions for all databases
Dbadminanydatabase: Only available in the Admin database, giving the user dbadmin permissions for all databases.
root: Available only in the admin database. Super account, Super privilege

Create a Super Administrator

Manage all the databases, you must go to the admin under the creation (use admin), delete also to the corresponding library operation

Create user use Admindb.createuser under mongo#admin ({User:"Root",pwd:"Root", roles: [{role:"Root"Db:"Admin"}]}) #test下创建用户use Testdb.createuser ({User:"Test",pwd:"Test", roles: [{role:"Root"Db:"Test"}]}) #查看用户show users; #删除用户> Db.dropuser ('Root');true> Show Users;

Verifying user Presence

# Note : After the user is created, it takes effect after the profile opens Auth authentication and restarts.

vim/application/mongodb/conf/mongodb1.confsecurity:  authorization:enabled

Method 1

In-Database validation

> use adminswitched to DB admin> Db.auth ("root","root " ); 1 #查看系统用户表中数据, view the permissions of the control only under the admin database
# All user information is stored in the System.user under the Admin database

> Db.system.users. Find (). Pretty ()
{    "_id":"Admin.root",    "User":"Root",    "DB":"Admin",    "Credentials" : {        "Scram-sha-1" : {            "IterationCount":10000,            "Salt":"9ed3clyzpbthtzzdpqbg9w==",            "Storedkey":"qdoewi/2uhumwjjubhopsa+cleo=",            "Serverkey":"pc8yoq1guah7a+zieycelpjiny0="        }    },    "Roles" : [        {            "role":"Root",            "DB":"Admin"        }    ]}

Method 2

Out-of-database validation

[Email protected] ~]$ mongo-uroot-3.2. 8 Connecting To:admin

Defines the specified database permission validation, read-only user

[Email protected] ~]$ Mongo-utest-ptest Test> Db.createcollection ('b'); # CREATE table {"OK":1 }>Show tables; # display table b> Db.b.insert ({"2":"b"}) # Insert Data writeresult ({"ninserted":1 })> db.b.Find(). Pretty (); # format print data {"_id": ObjectId ("5a4dd8d22a31eab1f0bbdc67"),"2":"b" }>db.b.remove ({}) # delete data writeresult ({"nremoved":1 })> db.b.Find(). Pretty ();

Create read and write permissions to multiple databases

Use appdb.createuser ({User:"app",    pwd:"app", roles: [{role:"ReadWrite"Db:"app"}, {role:"Read"Db:"Test"}]}) #app用户登录测试

Delete User

10.0. 0.131/adminuse appdb.dropuser ("app")

SQL language vs. crud language comparison

MongoDB CRUD Operations http://www.mongoing.com/docs/crud.html

Schema

SQL Schema Statements

MongoDB Schema Statements

CREATE TABLE Users (

ID Mediumint not NULL

Auto_increment,

user_id Varchar (30),

Age number,

Status char (1),

PRIMARY KEY (ID)

)

Implicitly created on first insert () operation. The primary

Key _idis automatically added if _id field is not specified.

Db.users.insert ({

USER_ID: "Abc123",

Age:55,

Status: "A"

} )

However, you can also explicitly create a collection:

Db.createcollection ("Users")

ALTER TABLE Users

ADD join_date DATETIME

There is no data structure concept at the collection level. At document level, however, the $set can be

The update action adds a column to the document.

Db.users.update (

{ },

{$set: {join_date:new date ()}},

{Multi:true}

)

ALTER TABLE Users

DROP COLUMN Join_date

There is no data structure concept at the collection level. At document level, however, you can pass $unset

The update operation removes the column from the document.

Db.users.update (

{ },

{$unset: {join_date: ' "}},

{Multi:true}

)

CREATE INDEX IDX_USER_ID_ASC

On users (USER_ID)

Db.users.createIndex ({user_id:1})

CREATE INDEX

Idx_user_id_asc_age_desc

On users (user_id, age DESC)

Db.users.createIndex ({user_id:1, Age:-1})

DROP TABLE Users

Db.users.drop ()

Insert statement

SQL INSERT Statements

MongoDB Insert () statements

INSERT into

Users (USER_ID,

Age

Status

VALUES ("bcd001",

45,

"A")

Db.users.insert (

{user_id: "bcd001", Age:

Status: "A"}

)


Query class

SQL SELECT Statements

MongoDB Find () statements

SELECT *

From users

Db.users.find ()

SELECT ID,

USER_ID,

Status

From users

Db.users.find (

{ },

{user_id:1, status:1, _id:0}

)

SELECT user_id, status

From users

Db.users.find (

{ },

{user_id:1, status:1}

)

SELECT *

From users

WHERE status = "A"

Db.users.find (

{status: ' A '}

)

SELECT user_id, status

From users

WHERE status = "A"

Db.users.find (

{status: ' A '},

{user_id:1, status:1, _id:0}

)

Data Update operations

SQL Update Statements

MongoDB Update () statements

UPDATE Users

SET status = "C"

WHERE Age > 25

Db.users.update (

{age: {$gt: 25}},

{$set: {status: ' C '}},

{Multi:true}

)

UPDATE Users

SET age = Age + 3

WHERE status = "A"

Db.users.update (

{status: ' A '},

{$inc: {age:3}},

{Multi:true}

)

Data Delete operations

SQL Delete Statements

MongoDB Remove () statements

DELETE from users

WHERE status = "D"

Db.users.remove ({status: "D"})

DELETE from users

Db.users.remove ({})

MongoDB Simple to use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.