mongodb基础操作

1.与数据库相关

(1)切换/创建数据库

> use ikidana;
switched to db ikidana

当数据库不存在的时候,就会执行创建操作。

如果你创建了一个数据库但是并没有向里面写入任何数据或者创建任何用户,那么这个数据库并没有真正被创建出来。

(2)查询所有数据库

> show dbs;
admin    0.000GB
ikidana  0.000GB
local    0.000GB

(3)删除当前使用的数据库

> show dbs
admin    0.000GB
ikidana  0.000GB
local    0.000GB
test     0.000GB
> db.dropDatabase();
{ "dropped" : "test", "ok" : 1 }
> show dbs
admin    0.000GB
ikidana  0.000GB
local    0.000GB

(4)查询当前使用的数据库

> db
admin
> db.getName()
admin

(5)显示当前DB的状态

> db.stats()
{
    "db" : "admin",
    "collections" : 2,
    "views" : 0,
    "objects" : 4,
    "avgObjSize" : 182.5,
    "dataSize" : 730,
    "storageSize" : 65536,
    "numExtents" : 0,
    "indexes" : 4,
    "indexSize" : 131072,
    "ok" : 1
}

(6)当前DB的版本

> db.version()
3.4.22

2.与用户相关

MongoDB role类型:

  • 数据库用户角色(Database User Roles)

    read:授予User只读数据的权限
    readWrite:授予User读写数据的权限

  • 数据库管理角色(Database Administration Roles):

    dbAdmin:在当前dB中执行管理操作
    dbOwner:在当前DB中执行任意操作
    userAdmin:在当前DB中管理User

  • 备份和还原角色(Backup and Restoration Roles):

    backup
    restore

  • 跨库角色(All-Database Roles):

    readAnyDatabase:授予在所有数据库上读取数据的权限
    readWriteAnyDatabase:授予在所有数据库上读写数据的权限
    userAdminAnyDatabase:授予在所有数据库上管理User的权限
    dbAdminAnyDatabase:授予管理所有数据库的权限

  • 集群管理角色(Cluster Administration Roles):

    clusterAdmin:授予管理集群的最高权限
    clusterManager:授予管理和监控集群的权限
    clusterMonitor:授予监控集群的权限,对监控工具具有readonly的权限
    hostManager:管理Server

(1)查询当前数据库的所有用户

> use ikidana;
switched to db ikidana
> show users;
{
    "_id" : "ikidana.kebi",
    "userId" : BinData(4,"8yldjVL8TxKjwNYhpmZ+Yg=="),
    "user" : "kebi",
    "db" : "ikidana",
    "roles" : [
        {
            "role" : "dbAdmin",
            "db" : "ikidana"
        }
    ]
}
{
    "_id" : "ikidana.yueji",
    "userId" : BinData(4,"OIbrRRo+QwmhZmw2ECekPQ=="),
    "user" : "yueji",
    "db" : "ikidana",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "ikidana"
        }
    ]
}

(2)创建管理员用户

> use admin
switched to db admin
> db.createUser({user:"admin",pwd:"password",roles:["root"]})
Successfully added user: { "user" : "admin", "roles" : [ "root" ] }

(3)认证登录(当前数据库的用户)

> db.auth("kebi","123")
1
> db.auth("kebi","123456")
Error: Authentication failed.
0

(4)添加数据库用户

> db.createUser({user:"yueji",pwd:"123456",roles:[{role:"readWrite",db:"ikidana"}]})
Successfully added user: {
    "user" : "yueji",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "ikidana"
        }
    ]
}

(5)查看系统用户

> db.system.users.find()
{ "_id" : "admin.admin", "userId" : BinData(4,"6QN49Zz2T/qrReics+1kIQ=="), "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "lCQUD/gOOtWhah/I86pnbQ==", "storedKey" : "EbuFk6exHsvDzpe65P6oCqUOGDU=", "serverKey" : "sLj3qBhj2FBXJ3xhtapq4fRzT6g=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.yueji", "userId" : BinData(4,"a7Jqzjg8RD6LewZU5sh4RA=="), "user" : "yueji", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "8KKhrQ2XFgk/9iJQbGTDxA==", "storedKey" : "4CzO4FdMnbq20IoW1+zXBJMiBQA=", "serverKey" : "TwQSkGtHpsY8a9WTaWyLfIPIzS0=" } }, "roles" : [ { "role" : "read", "db" : "admin" } ] }
{ "_id" : "ikidana.yueji", "userId" : BinData(4,"OIbrRRo+QwmhZmw2ECekPQ=="), "user" : "yueji", "db" : "ikidana", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "BXriW8BvaltTyHbrg7q1Hw==", "storedKey" : "W5EnO6ICteuuCDELhFO5OljKUuw=", "serverKey" : "DVZqiufUt8DD4T6UHhNLoTRHAR0=" } }, "roles" : [ { "role" : "readWrite", "db" : "ikidana" } ] }
{ "_id" : "ikidana.kebi", "userId" : BinData(4,"8yldjVL8TxKjwNYhpmZ+Yg=="), "user" : "kebi", "db" : "ikidana", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "bToeXegvlq9Zf6OgyyAE8A==", "storedKey" : "YpgLtzd/z3JBz/memJatHRr5/WI=", "serverKey" : "3VG8GrVgkUEtwc5zc4iJScaEEmM=" } }, "roles" : [ { "role" : "dbAdmin", "db" : "ikidana" } ] }

(6)删除用户

> use ikidana;
switched to db ikidana
> show users;
{
    "_id" : "ikidana.kebi",
    "userId" : BinData(4,"8yldjVL8TxKjwNYhpmZ+Yg=="),
    "user" : "kebi",
    "db" : "ikidana",
    "roles" : [
        {
            "role" : "dbAdmin",
            "db" : "ikidana"
        }
    ]
}
{
    "_id" : "ikidana.yueji",
    "userId" : BinData(4,"OIbrRRo+QwmhZmw2ECekPQ=="),
    "user" : "yueji",
    "db" : "ikidana",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "ikidana"
        }
    ]
}
> db.dropUser("kebi")
true
> show users;
{
    "_id" : "ikidana.yueji",
    "userId" : BinData(4,"OIbrRRo+QwmhZmw2ECekPQ=="),
    "user" : "yueji",
    "db" : "ikidana",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "ikidana"
        }
    ]
}

3.与Collection聚集集合

(1)创建一个聚集集合

> db.createCollection("yue-test")
{ "ok" : 1 }

(2)得到指定名称的聚集集合

> db.getCollection("info")
ikidana.info

(3)得到当前db的所有聚集集合

> db.getCollectionNames()
[ "info", "test", "yue-test" ]
> show collections
info
test
yue-test

(4)显示当前db所有聚集索引的状态

 db.printCollectionStats();

4.文档操作

(1)插入文档

单条插入:

> db.createCollection("blog")
{ "ok" : 1 }
> post={
...     "title":"blog post",
...     "content":"blog content",
...     "date":"2011-12-12"
... }
{ "title" : "blog post", "content" : "blog content", "date" : "2011-12-12" }
> db.blog.insert(post)
WriteResult({ "nInserted" : 1 })

多条一起插入:

> post1={
...     "title":"blog post1",
...     "content":"blog content",
...     "date":"2011-12-12"
... }
{
    "title" : "blog post1",
    "content" : "blog content",
    "date" : "2011-12-12"
}
> post2={
...     "title":"blog post2",
...     "content":"blog content",
...     "date":"2011-12-12"
... }
{
    "title" : "blog post2",
    "content" : "blog content",
    "date" : "2011-12-12"
}
> db.blog.insert([post1,post2])
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

(2)查看文档

查看某一个集合的所有文档:

> db.blog.find()
{ "_id" : ObjectId("5d424e69828c9a3faa37cd5e"), "title" : "blog post", "content" : "blog content", "date" : "2011-12-12" }
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd5f"), "title" : "blog post1", "content" : "blog content", "date" : "2011-12-12" }
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd60"), "title" : "blog post2", "content" : "blog content", "date" : "2011-12-12" }

查看某一个集合的所有文档,并格式化显示:

> db.blog.find().pretty()
{
    "_id" : ObjectId("5d424e69828c9a3faa37cd5e"),
    "title" : "blog post",
    "content" : "blog content",
    "date" : "2011-12-12"
}
{
    "_id" : ObjectId("5d424e8d828c9a3faa37cd5f"),
    "title" : "blog post1",
    "content" : "blog content",
    "date" : "2011-12-12"
}
{
    "_id" : ObjectId("5d424e8d828c9a3faa37cd60"),
    "title" : "blog post2",
    "content" : "blog content",
    "date" : "2011-12-12"
}

(3)删除文档

> db.blog.find()
{ "_id" : ObjectId("5d424e69828c9a3faa37cd5e"), "title" : "blog post", "content" : "blog content", "date" : "2011-12-12" }
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd5f"), "title" : "blog post1", "content" : "blog content", "date" : "2011-12-12" }
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd60"), "title" : "blog post2", "content" : "blog content", "date" : "2011-12-12" }
> db.blog.remove({"title":"blog post"})
WriteResult({ "nRemoved" : 1 })
> db.blog.find()
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd5f"), "title" : "blog post1", "content" : "blog content", "date" : "2011-12-12" }
{ "_id" : ObjectId("5d424e8d828c9a3faa37cd60"), "title" : "blog post2", "content" : "blog content", "date" : "2011-12-12" }

删除文档的方式是非常灵活的,你可以按照文档中的任意属性来进行删除操作。

原文地址:https://www.cnblogs.com/yangmingxianshen/p/11281093.html