mongodb语法实践

Days(11.14)

        mongodb之前都是负责搭建、维护、备份、监控等操作。闲时来总结一下语法。

查询

根据条件查询数据量

        登录数据库操作

1
> db.getCollection('Tables').find({"字段":"条件","字段":"条件"}).count();

        查看数据库表

1
> show collections

        查看mongodb的连接数

1
> db.serverStatus().connections

创建

创建用户、数据库

  • 创建数据库

    1
    > use xxx
  • 创建一个用户,拥有基本的读写权限

    1
    > db.createUser({user:"xxx",pwd:"xxx",roles:[{role:"readWrite",db:"xxx"}]})
  • 创建用户需要赋予dbAdmin权限

dbAdmin: 允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile

1
> db.createUser({user:"demo",pwd:"demo",roles:[{role:"readWrite",db:"kxlChannel"},{role:"dbAdmin",db:"kxlChannel"}]})

: role 权限要是readWrite,不能赋予dbadmin,否则不能操作数据库

删除

删除账户和数据库

  • 删除账户

    1
    > db.dropUser("xxx")
  • 删除数据库

    1
    2
    3
    4
    5
    > db.dropDatabase("xxx")

    # 还可以
    > use names
    > db.dropDatabase()

索引

创建索引

1
2
> db.表.ensureIndex({"字段":1},{"unique":true})
> db.表.ensureIndex({"字段":1},{"unique":true})

查看索引

1
> db.表.getIndexes()

        查看表数据是否引用了索引

1
> db.表.find({"字段":"值"}).explain()

删除指定索引

1
> db.表.dropIndex("索引")

        删除表全部索引

1
> db.表.dropIndexes()

备份

根据条件导出部分数据

1
$  mongoexport --db=数据库 --collection=表 --username=账户 --password=密码 --authenticationDatabase=认证的数据库  --query='{"条件","条件"}' --fields="导出的字段" --type=csv --out=/home/ll
  • 参数介绍:
    –db: 数据库
    –collection: 表
    –username: 账户
    –password: 密码
    –authenticationDatabase: 需要认证的数据库
    –query: 条件
    –fields: 导出的字段
    –type: 导出的格式,默认是json,这里导出为csv,支持两种json和csv格式
    –out: 导出路径文件

更多参数参考 –help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
general options:
--help print usage
--version print the tool version and exit
verbosity options:
-v, --verbose=<level> more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a numeric value, e.g. --verbose=N)
--quiet hide all log output
connection options:
-h, --host=<hostname> mongodb host to connect to (setname/host1,host2 for replica sets)
--port=<port> server port (can also use --host hostname:port)
kerberos options:
--gssapiServiceName=<service-name> service name to use when authenticating using GSSAPI/Kerberos ('mongodb' by default)
--gssapiHostName=<host-name> hostname to use when authenticating using GSSAPI/Kerberos (remote server's address by default)
ssl options:
--ssl connect to a mongod or mongos that has ssl enabled
--sslCAFile=<filename> the .pem file containing the root certificate chain from the certificate authority
--sslPEMKeyFile=<filename> the .pem file containing the certificate and key
--sslPEMKeyPassword=<password> the password to decrypt the sslPEMKeyFile, if necessary
--sslCRLFile=<filename> the .pem file containing the certificate revocation list
--sslAllowInvalidCertificates bypass the validation for server certificates
--sslAllowInvalidHostnames bypass the validation for server name
--sslFIPSMode use FIPS mode of the installed openssl library
authentication options:
-u, --username=<username> username for authentication
-p, --password=<password> password for authentication
--authenticationDatabase=<database-name> database that holds the user's credentials
--authenticationMechanism=<mechanism> authentication mechanism to use
namespace options:
-d, --db=<database-name> database to use
-c, --collection=<collection-name> collection to use
uri options:
--uri=mongodb-uri mongodb uri connection string
output options:
-f, --fields=<field>[,<field>]* comma separated list of field names (required for exporting CSV) e.g. -f "name,age"
--fieldFile=<filename> file with field names - 1 per line
--type=<type> the output format, either json or csv (defaults to 'json') (default: json)
-o, --out=<filename> output file; if not specified, stdout is used
--jsonArray output to a JSON array rather than one object per line
--pretty output JSON formatted to be human-readable
--noHeaderLine export CSV data without a list of field names at the first line
querying options:
-q, --query=<json> query filter, as a JSON string, e.g., '{x:{$gt:1}}'
--queryFile=<filename> path to a file containing a query filter (JSON)
-k, --slaveOk allow secondary reads if available (default true) (default: false)
--readPreference=<string>|<json> specify either a preference name or a preference json object
--forceTableScan force a table scan (do not use $snapshot)
--skip=<count> number of documents to skip
--limit=<count> limit the number of documents to export
--sort=<json> sort order, as a JSON string, e.g. '{x:1}'
--assertExists if specified, export fails if the collection does not exist (default: false)

mongodb 备份脚本可以参考本人写的

坚持原创技术分享,您的支持将鼓励我继续创作!
0%