mongoDB学习笔记六

本文介绍了MongoDB的进阶操作,包括如何删除和查看数据库中的集合,创建和转换固定集合,以及如何使用gridFS进行文件存储。详细讲解了gridFS的常用命令,如上传、下载、查询和删除文件,并通过实际操作展示了mongofiles工具的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第七章 进阶指南

 

一数据库命令

 

命令的工作原理

#删除集合的操作

db.dropTest.drop()

 

#也可以使用如下操作,同上面的效果一样

#显示数据库中的所有集合

> show collections

blog

blog.posts

dropTest

foo

prices

Users

 

#删除集合

>db.runCommand({"drop":"dropTest"});

{ "ns" :"test.dropTest", "nIndexesWas" : 1, "ok" : 1 }

> show collections

blog

blog.posts

foo

prices

users

 

命令参考

#取得命令的最新参考

Command

Attributes

Help

replSetGetStatus

R S A

Report status of a replica set from the POV of this server
{ replSetGetStatus : 1 }
http://dochub.mongodb.org/core/replicasetcommands

killOp

R S A

 

rolesInfo

R

Returns information about roles.

saslContinue

R S

Subsequent steps in a SASL authentication conversation.

dropIndexes

W

drop indexes for a collection

删除集合里name的索引

drop

W

drop a collection
{drop : <collectionName>}

删除当前数据库的所有数据

cloneCollectionAsCapped

W

{ cloneCollectionAsCapped:<fromName>, toCollection:<toName>, size:<sizeInBytes> }

dbHash

R S

 

planCacheSetFilter

R

Sets index filter for a query shape. Overrides existing filter.

_recvChunkStart

R A

internal

writebacklisten

R S A

v3.0 disallowed internal command, present for compatibility only

reIndex

W S

re-index a collection

revokeRolesFromUser

W

Revokes roles from a user.

parallelCollectionScan

R S

 

getnonce

R S

internal

geoNear

R S

http://dochub.mongodb.org/core/geo

touch

R S

touch collection
Page in all pages of memory containing every extent for the given collection
{ touch : <collection_name>, [data : true] , [index : true] }
at least one of data or index must be true; default is both are false

getMore

R S

retrieve more results from an existing cursor

profile

W S

enable or disable performance profiling
{ profile : <n> }
0=off 1=log slow ops 2=log all
-1 to get current values
http://docs.mongodb.org/manual/reference/command/profile/

handshake

R S

internal

compact

R S

compact collection
warning: this operation locks the database and is slow. you can cancel with killOp()
{ compact : <collection_name>, [force:<bool>], [validate:<bool>],
[paddingFactor:<num>], [paddingBytes:<num>] }
force - allows to run on a replica set primary
validate - check records are noncorrupt before adding to newly compacting extents. slower but safer (defaults to true in this version)

group

R

http://dochub.mongodb.org/core/aggregation

分组

_recvChunkCommit

R A

internal

splitChunk

R A

internal command usage only
example:
{ splitChunk:"db.foo" , keyPattern: {a:1} , min : {a:100} , max: {a:200} { splitKeys : [ {a:150} , ... ]}

planCacheListPlans

R

Displays the cached plans for a query shape.

dropDatabase

W

drop (delete) this database

删除数据库

replSetGetRBID

R S A

 

shardingState

W A

 

filemd5

R S

example: { filemd5 : ObjectId(aaaaaaa) , root : "fs" }

authenticate

R S

internal

killCursors

R S

kill a list of cursor ids

connectionStatus

R S

Returns connection-specific information such as logged-in users and their roles

联接状态

mergeChunks

R A

Merge Chunks command
usage: { mergeChunks : <ns>, bounds : [ <min key>, <max key> ], (opt) epoch : <epoch>, (opt) config : <configdb string>, (opt) shardName : <shard name> }

logout

R S

de-authenticate

driverOIDTest

R S

 

replSetSyncFrom

R S A

{ replSetSyncFrom : "host:port" }
Change who this member is syncing from.

unsetSharding

R S A

internal

isMaster

R S

Check if this server is primary for a replica pair/set; also if it is --master or --slave in simple master/slave setups.
{ isMaster : 1 }

是不是主服务器

_transferMods

R A

internal

planCacheClearFilters

R

Clears index filter for a single query shape or, if the query shape is omitted, all filters for the collection.

update

R

update documents

更新文档

ping

R S

a way to check that the server is alive. responds immediately even if server is in a db lock.

检查服务器联接是否正常

grantPrivilegesToRole

W

Grants privileges to a role

createIndexes

R

 

connPoolStats

R S

stats about connections between servers in a replica set or sharded cluster.

联接池状态

invalidateUserCache

R S A

Invalidates the in-memory cache of user information

listDatabases

R A

list databases on this server

列出服务器上的所有数据库

dropAllRolesFromDatabase

W

Drops all roles from the given database. Before deleting the roles completely it must remove them from any users or other roles that reference them. If any errors occur in the middle of that process it's possible to be left in a state where the roles have been removed from some user/roles but otherwise still exist.

shutdown

R S A

shutdown the database. must be ran against admin db and either (1) ran from localhost or (2) authenticated. If this is a primary in a replica set and there is no member within 10 seconds of its optime, it will not shutdown without force : true. You can also specify timeoutSecs : N to wait N seconds for other members to catch up.

connPoolSync

R S

internal

setShardVersion

R S A

internal

fsync

R S A

http://dochub.mongodb.org/core/fsynccommand

getCmdLineOpts

R S A

get argv

usersInfo

R

Returns information about users.

_getUserCacheGeneration

R S A

internal

authSchemaUpgrade

W A

Upgrades the auth data storage schema

convertToCapped

W

{ convertToCapped:<fromCollectionName>, size:<sizeInBytes> }

planCacheListQueryShapes

R

Displays all query shapes in a collection.

_mergeAuthzCollections

W A

Internal command used by mongorestore for updating user/role data

count

R

count objects in collection

logRotate

R S A

 

listIndexes

R

list indexes for a collection

replSetDeclareElectionWinner

R S A

 

insert

R

insert documents

插入文档

geoSearch

R S

 

getParameter

R S A

get administrative option(s)
example:
{ getParameter:1, notablescan:1 }
supported:
ShardingTaskExecutorPoolHostTimeoutMS
ShardingTaskExecutorPoolMaxSize
ShardingTaskExecutorPoolMinSize
ShardingTaskExecutorPoolRefreshRequirementMS
ShardingTaskExecutorPoolRefreshTimeoutMS
authSchemaVersion
authenticationMechanisms
clusterAuthMode
connPoolMaxConnsPerHost
connPoolMaxShardedConnsPerHost
cursorTimeoutMillis
diagnosticDataCollectionDirectorySizeMB
diagnosticDataCollectionEnabled
diagnosticDataCollectionFileSizeMB
diagnosticDataCollectionPeriodMillis
diagnosticDataCollectionSamplesPerChunk
diagnosticDataCollectionSamplesPerInterimUpdate
disableJavaScriptJIT
enableCollectionLocking
enableLocalhostAuthBypass
enableReplSnapshotThread
enableTestCommands
failIndexKeyTooLong
internalAggregationLookupBatchSize
internalGeoNearQuery2DMaxCoveringCells
internalGeoPredicateQuery2DMaxCoveringCells
internalQueryCacheEvictionRatio
internalQueryCacheFeedbacksStored
internalQueryCacheSize
internalQueryEnumerationMaxIntersectPerAnd
internalQueryEnumerationMaxOrSolutions
internalQueryExecMaxBlockingSortBytes
internalQueryExecYieldIterations
internalQueryExecYieldPeriodMS
internalQueryForceIntersectionPlans
internalQueryMaxScansToExplode
internalQueryPlanEvaluationCollFraction
internalQueryPlanEvaluationMaxResults
internalQueryPlanEvaluationWorks
internalQueryPlanOrChildrenIndependently
internalQueryPlannerEnableHashIntersection
internalQueryPlannerEnableIndexIntersection
internalQueryPlannerMaxIndexedSolutions
internalQueryS2GeoCoarsestLevel
internalQueryS2GeoFinestLevel
internalQueryS2GeoMaxCells
internalSCCAllowFastestAuthConfigReads
internalSCCAllowFastestMetadataConfigReads
javascriptProtection
journalCommitInterval
logComponentVerbosity
logLevel
logUserIds
maxSyncSourceLagSecs
newCollectionsUsePowerOf2Sizes
notablescan
priorityTakeoverFreshnessWindowSeconds
queueForMigrationCommit
quiet
recoverShardingState
replApplyBatchSize
replElectionTimeoutOffsetLimitFraction
replIndexPrefetch
replMonitorMaxFailedChecks
replSnapshotThreadThrottleMicros
replWriterThreadCount
saslHostName
saslServiceName
saslauthdPath
scramIterationCount
skipCorruptDocumentsWhenCloning
sslMode
startupAuthSchemaValidation
syncdelay
taskExecutorPoolSize
tcmallocAggressiveMemoryDecommit
tcmallocMaxTotalThreadCacheBytes
testingSnapshotBehaviorInIsolation
textSearchEnabled
timeOutMonitoringReplicaSets
traceExceptions
traceWriteConflictExceptions
ttlMonitorEnabled
ttlMonitorSleepSecs
wiredTigerConcurrentReadTransactions
wiredTigerConcurrentWriteTransactions
wiredTigerEngineRuntimeConfig
{ getParameter:'*' } to get everything

delete

R

delete documents

删除文档

distinct

R

{ distinct : 'collection name' , key : 'a.b' , query : {} }

replSetStepDown

R S A

{ replSetStepDown : <seconds> }
Step down as primary. Will not try to reelect self for the specified time period (1 minute if no numeric secs value specified).
(If another member with same priority takes over in the meantime, it will stay primary.)
http://dochub.mongodb.org/core/replicasetcommands

find

R

query for documents

查询文档

validate

R S

Validate contents of a namespace by scanning its data structures for correctness. Slow.
Add full:true option to do a more thorough check

setParameter

R S A

set administrative option(s)
{ setParameter:1, <param>:<value> }
supported:
ShardingTaskExecutorPoolHostTimeoutMS
ShardingTaskExecutorPoolMaxSize
ShardingTaskExecutorPoolMinSize
ShardingTaskExecutorPoolRefreshRequirementMS
ShardingTaskExecutorPoolRefreshTimeoutMS
authSchemaVersion
authenticationMechanisms
clusterAuthMode
connPoolMaxConnsPerHost
connPoolMaxShardedConnsPerHost
cursorTimeoutMillis
diagnosticDataCollectionDirectorySizeMB
diagnosticDataCollectionEnabled
diagnosticDataCollectionFileSizeMB
diagnosticDataCollectionPeriodMillis
diagnosticDataCollectionSamplesPerChunk
diagnosticDataCollectionSamplesPerInterimUpdate
disableJavaScriptJIT
enableCollectionLocking
enableLocalhostAuthBypass
enableReplSnapshotThread
enableTestCommands
failIndexKeyTooLong
internalAggregationLookupBatchSize
internalGeoNearQuery2DMaxCoveringCells
internalGeoPredicateQuery2DMaxCoveringCells
internalQueryCacheEvictionRatio
internalQueryCacheFeedbacksStored
internalQueryCacheSize
internalQueryEnumerationMaxIntersectPerAnd
internalQueryEnumerationMaxOrSolutions
internalQueryExecMaxBlockingSortBytes
internalQueryExecYieldIterations
internalQueryExecYieldPeriodMS
internalQueryForceIntersectionPlans
internalQueryMaxScansToExplode
internalQueryPlanEvaluationCollFraction
internalQueryPlanEvaluationMaxResults
internalQueryPlanEvaluationWorks
internalQueryPlanOrChildrenIndependently
internalQueryPlannerEnableHashIntersection
internalQueryPlannerEnableIndexIntersection
internalQueryPlannerMaxIndexedSolutions
internalQueryS2GeoCoarsestLevel
internalQueryS2GeoFinestLevel
internalQueryS2GeoMaxCells
internalSCCAllowFastestAuthConfigReads
internalSCCAllowFastestMetadataConfigReads
javascriptProtection
journalCommitInterval
logComponentVerbosity
logLevel
logUserIds
maxSyncSourceLagSecs
newCollectionsUsePowerOf2Sizes
notablescan
priorityTakeoverFreshnessWindowSeconds
queueForMigrationCommit
quiet
recoverShardingState
replApplyBatchSize
replElectionTimeoutOffsetLimitFraction
replIndexPrefetch
replMonitorMaxFailedChecks
replSnapshotThreadThrottleMicros
replWriterThreadCount
saslHostName
saslServiceName
saslauthdPath
scramIterationCount
skipCorruptDocumentsWhenCloning
sslMode
startupAuthSchemaValidation
syncdelay
taskExecutorPoolSize
tcmallocAggressiveMemoryDecommit
tcmallocMaxTotalThreadCacheBytes
testingSnapshotBehaviorInIsolation
textSearchEnabled
timeOutMonitoringReplicaSets
traceExceptions
traceWriteConflictExceptions
ttlMonitorEnabled
ttlMonitorSleepSecs
wiredTigerConcurrentReadTransactions
wiredTigerConcurrentWriteTransactions
wiredTigerEngineRuntimeConfig

features

R S

return build level feature settings

repairDatabase

W S

repair database. also compacts. note: slow.

修复并压缩当前数据库

collStats

R S

{ collStats:"blog.posts" , scale : 1 } scale divides sizes e.g. for KB use 1024
avgObjSize - in bytes

getShardVersion

R A

example: { getShardVersion : 'alleyinsider.foo' }

currentOp

R S A

 

listCollections

R

list collections for this db

显不当前数据库中的集合

whatsmyuri

R S

{whatsmyuri:1}

replSetInitiate

R S A

Initiate/christen a replica set.
http://dochub.mongodb.org/core/replicasetcommands

grantRolesToUser

W

Grants roles to a user.

shardConnPoolStats

R S

stats about the shard connection pool

serverStatus

R S

returns lots of administrative server statistics

服务器的管理统计信息

checkShardingIndex

R

Internal command.

resetError

R S

reset error state (used with getpreverror)

revokeRolesFromRole

W

Revokes roles from another role.

fsyncUnlock

R S A

 

replSetHeartbeat

R S A

 

findAndModify

W

{ findAndModify: "collection", query: {processed:false}, update: {$set: {processed:true}}, new: true}
{ findAndModify: "collection", query: {processed:false}, remove: true, sort: {priority:-1}}
Either update or remove is required, all other fields have default values.
Output is in the "value" field

返回已更新的文档

dbStats

R S

Get stats on a database. Not instantaneous. Slower for databases with large .ns files.
Example: { dbStats:1, scale:1 }

renameCollection

W A

example: { renameCollection: foo.a, to: bar.b }

集合重命名

forceerror

R S

for testing purposes only. forces a user assertion exception

clone

W

clone this database from an instance of the db on another host
{clone: "host13"[, slaveOk: <bool>]}

cleanupOrphaned

R A

 

dropUser

W

Drops a single user.

getPrevError

R S

check for errors since last reseterror commandcal

dropAllUsersFromDatabase

W

Drops all users for a single database.

appendOplogNote

R A

Adds a no-op entry to the oplog

applyOps

W

internal (sharding)
{ applyOps : [ ] , preCondition : [ { ns : ... , q : ... , res : ... } ] }

availableQueryOptions

R S

 

replSetFreeze

R S A

{ replSetFreeze : <seconds> }'freeze' state of member to the extent we can do that. What this really means is that
this node will not attempt to become primary until the time period specified expires.
You can call again with {replSetFreeze:0} to unfreeze sooner.
A process restart unfreezes the member also.

http://dochub.mongodb.org/core/replicasetcommands

updateRole

W

Used to update a role

replSetMaintenance

R S A

{ replSetMaintenance : bool }
Enable or disable maintenance mode.

updateUser

W

Used to update a user, for example to change its password

_recvChunkAbort

R A

internal

replSetReconfig

R S A

Adjust configuration of a replica set
{ replSetReconfig : config_object }
http://dochub.mongodb.org/core/replicasetcommands

splitVector

R

Internal command.
examples:
{ splitVector : "blog.post" , keyPattern:{x:1} , min:{x:10} , max:{x:20}, maxChunkSize:200 }
maxChunkSize unit in MBs
May optionally specify 'maxSplitPoints' and 'maxChunkObjects' to avoid traversing the whole chunk

{ splitVector : "blog.post" , keyPattern:{x:1} , min:{x:10} , max:{x:20}, force: true }
'force' will produce one split point even if data is small; defaults to false
NOTE: This command may take a while to run

dropRole

W

Drops a single role. Before deleting the role completely it must remove it from any users or roles that reference it. If any errors occur in the middle of that process it's possible to be left in a state where the role has been removed from some user/roles but otherwise still exists.

删除角色

hostInfo

R S

returns information about the daemon's host

revokePrivilegesFromRole

W

Revokes privileges from a role

createUser

W

Adds a user to the system

添加系统用户

getLog

R S A

{ getLog : '*' } OR { getLog : 'global' }

diagLogging

W S A

http://dochub.mongodb.org/core/monitoring

copydbgetnonce

R A

get a nonce for subsequent copy db request from secure server
usage: {copydbgetnonce: 1, fromhost: <hostname>}

explain

R

explain database reads and writes

replSetUpdatePosition

R S A

 

replSetFresh

R S A

 

_migrateClone

R A

internal

getShardMap

R S A

lists the set of shards known to this instance

mapReduce

R S

Run a map/reduce operation on the server.
Note this is used for aggregation, not querying, in MongoDB.
http://dochub.mongodb.org/core/mapreduce

_recvChunkStatus

R A

internal

aggregate

R

{ pipeline: [ { $operator: {...}}, ... ], explain: <bool>, allowDiskUse: <bool>, cursor: {batchSize: <number>} }
See http://dochub.mongodb.org/core/aggregation for more details.

planCacheClear

R

Drops one or all cached queries in a collection.

moveChunk

R A

should not be calling this directly

copydbsaslstart

R A

Initialize a SASL auth session for subsequent copy db request from secure server

replSetGetConfig

R S A

Returns the current replica set configuration{ replSetGetConfig : 1 }
http://dochub.mongodb.org/core/replicasetcommands

createRole

W

Adds a role to the system

replSetRequestVotes

R S A

 

grantRolesToRole

W

Grants roles to another role.

cloneCollection

R

{ cloneCollection: <collection>, from: <host> [,query: <query_filter>] [,copyIndexes:<bool>] }
Copies a collection from one server to another. Do not use on a single server as the destination is placed at the same db.collection (namespace) as the source.

getLastError

R S

return error status of the last operation on this connection
options:
{ fsync:true } - fsync before returning, or wait for journal commit if running with --journal
{ j:true } - wait for journal commit if running with --journal
{ w:n } - await replication to n servers (including self) before returning
{ w:'majority' } - await replication to majority of set
{ wtimeout:m} - timeout for w in m milliseconds

查看对本集合执行的最后一次操作的错误信息

create

W

create a collection explicitly
{ create: <ns>[, capped: <bool>, size: <collSizeInBytes>, max: <nDocs>] }

创建集合

repairCursor

R S

 

resync

W S A

resync (from scratch) a stale slave or replica set secondary node.

planCacheListFilters

R

Displays index filters for all query shapes in a collection.

collMod

W

Sets collection options.
Example: { collMod: 'foo', usePowerOf2Sizes:true }
Example: { collMod: 'foo', index: {keyPattern: {a: 1}, expireAfterSeconds: 600} }

saslStart

R S

First step in a SASL authentication conversation.

currentOpCtx

R S

 

top

R S A

usage by collection, in micros

eval

R

DEPRECATED
Evaluate javascript at the server.
http://dochub.mongodb.org/core/serversidecodeexecution

copydb

R A

copy a database from another host to this host
usage: {copydb: 1, fromhost: <connection string>, fromdb: <db>, todb: <db>[, slaveOk: <bool>, username: <username>, nonce: <nonce>, key: <key>]}

listCommands

R S

get a list of all db commands

返回数据库命令

replSetElect

R S A

 

dataSize

R S

determine data size for a set of data in a certain range
example: { dataSize:"blog.posts", keyPattern:{x:1}, min:{x:10}, max:{x:55} }
min and max parameters are optional. They must either both be included or both omitted
keyPattern is an optional parameter indicating an index pattern that would be usefulfor iterating over the min/max bounds. If keyPattern is omitted, it is inferred from the structure of min.
note: This command may take a while to run

_isSelf

R S

{ _isSelf : 1 } INTERNAL ONLY

mapreduce.shardedfinish

R S

internal

buildInfo

R S

get version #, etc.
{ buildinfo:1 }

 

 

二固定集合

事先创建大小固定

固定集合像环形队列,队尾插入,空间满时,队首插入,删除原有

固定集合没有索引

 

创建固定集合

#创建容量为10000字节,文档上限为100的my_collections集合

>db.createCollection("my_collections",{capped:true,size:10000,max:100})

{ "ok" : 1 }

> show collections

blog

blog.posts

foo

my_collections

prices

users

 

将普通集合转为固定集合

db.runCommand({convertToCapped:”test,size:10000”})

 

自然排序

 

#按反向插入的顺序查询

Db.my_collections.find().sort({“natural”:-1})

 

尾部游标

 

三gridFS存储文件

用来存储大于进制文件的机制

Mongofiles 可以用来在gridFS中上传 下载 列示 查找和删除文件

查看mongofile的可用选项

C:\Users\Administrator>mongofiles --help

Usage:

 mongofiles <options> <command> <filename or _id>

 

Manipulate gridfs files using the commandline.

 

Possible commands include:

       list      - list all files;'filename' is an optional prefix which listed filenames must begin with  

列表显示 gridFS中的所有文件

 

       search    - search all files;'filename' is a substring which listed filenames must contain

查询文件

 

       put       - add a file withfilename 'filename'

上传文件到gridFS

       get       - get a file withfilename 'filename'

将gridFS中的文件写入到文件系统中(下载)

        get_id   - get a file with the given '_id'

根据id查询文件

       delete    - delete all files withfilename 'filename'

删除gridFS中指定文件

       delete_id - delete a file with the given '_id'

根据id删除文件

 

Seehttp://docs.mongodb.org/manual/reference/program/mongofiles/ for moreinformation.

 

general options:

     /help                                       printusage

     /version                                    print thetool version and

                                                 exit

 

verbosity options:

  /v,/verbose:<level>                            more detailed logoutput

                                                 (include multiple times for

                                                 more verbosity, e.g. -vvvvv,

                                                  or specify anumeric value,

                                                 e.g. --verbose=N)

     /quiet                                      hide alllog output

不显示输出日志

 

connection options:

  /h,/host:<hostname>                            mongodb host toconnect to

                                                 (setname/host1,host2 for

                                                 replica sets)

指定服务器名

     /port:<port>                                server port(can also use

                                                 --host hostname:port)

指定服务器端口号

 

ssl options:

     /ssl                                        connectto a mongod or mongos

                                                 that has ssl enabled

     /sslCAFile:<filename>                       the .pem file containingthe

                                                 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 containingthe

                                                 certificate revocation list

     /sslAllowInvalidCertificates                bypass the validation for

                                                 server certificates

     /sslAllowInvalidHostnames                   bypass the validation for

                                                 server name

     /sslFIPSMode                                use FIPS modeof the

                                                 installed openssl library

 

authentication options:

  /u,/username:<username>                        username forauthentication

  /p,/password:<password>                        password forauthentication

     /authenticationDatabase:<database-name>     database that holds the

                                                 user's credentials

     /authenticationMechanism:<mechanism>        authentication mechanism to

                                                 use

 

storage options:

  /d,/db:<database-name>                         database to use(default is

                                                 'test')

指定数据库.默认为test

  /l,/local:<filename>                           local filename forput|get

  /t,/type:                                     content/MIME type for put

                                                  (optional)

指定上传文件的类型

  /r,/replace                                   remove other files with same

                                                 name after put

 

     /prefix:<prefix>                            GridFS prefix touse (default

                                                 is 'fs')

     /writeConcern:<write-concern>               write concern options e.g.

                                                 --writeConcern majority,

                                                 --writeConcern '{w: 3,

                                                 wtimeout: 500, fsync: true,

                                                 j: true}' (defaults to

                                                  'majority')

 

query options:

     /readPreference:<string>|<json>             specify either a preference

                                                 name or a preference json

                                                 object

 

 

 

Mongofiles基本操作

#创建foo.txt文件,添加内容helloworld

D:\workspace_python>echo "helloworld!" >foo.txt

 

#查看当前目录下的所有文件,也可以使用dir命令.本机安装cygwin所以可以使用linux命令

D:\workspace_python>ls

chat        exception.py  hello.py         mysite           net          readTextFile.py  spam.py unittest   wordcount.py

database.py expand        internet         namedata.py      opencv      setup            sqlite3  urlib

dictTest.py foo.txt       makeTextFile.py  namedata_one.py  property.py spam             swig     winGUI.py

 

#查询gridFS中的所有文件

D:\workspace_python>mongofiles list

2017-01-11T16:27:50.872+0800    connected to: localhost

 

#上传文件foo.txt到gridFS

D:\workspace_python>mongofiles putfoo.txt

2017-01-11T16:27:55.705+0800    connected to: localhost

added file: foo.txt

 

#删除本地磁盘文件

D:\workspace_python>rm foo.txt

 

#查询当前目录的所有文件

D:\workspace_python>ls

chat        exception.py  internet         namedata.py      opencv          setup    sqlite3   urlib

database.py expand        makeTextFile.py  namedata_one.py  property.py     spam     swig     winGUI.py

dictTest.py hello.py      mysite           net              readTextFile.py  spam.py unittest  wordcount.py

 

#从gridFS 下载文件到本地磁盘

D:\workspace_python>mongofiles getfoo.txt

2017-01-11T16:28:32.492+0800    connected to: localhost

finished writing to foo.txt

 

#查看当前目录中的所有文件

D:\workspace_python>ls

chat        exception.py  hello.py         mysite           net          readTextFile.py  spam.py unittest   wordcount.py

database.py expand        internet         namedata.py      opencv       setup            sqlite3  urlib

dictTest.py foo.txt       makeTextFile.py  namedata_one.py  property.py spam             swig     winGUI.py

 

#查看foo.txt文件内容

D:\workspace_python>cat foo.txt

"hello world!"

 

#也可以使用记事本打开查看

D:\workspace_python>notepad foo.txt

 

#创建foo2.txt文件

D:\workspace_python>echo "helloworld2!" >foo2.txt

 

#上传文件到gridFS

D:\workspace_python>mongofiles putfoo2.txt

2017-01-11T16:35:28.767+0800    connected to: localhost

added file: foo2.txt

 

#列表显示所有文件内容

D:\workspace_python>mongofiles list

2017-01-11T16:35:33.935+0800    connected to: localhost

foo.txt 17

foo2.txt        18

 

 

#按照指定文件名查询文件

D:\workspace_python>mongofiles searchfoo2.txt

2017-01-11T16:35:49.086+0800    connected to: localhost

foo2.txt        18

 

#从gridFS中删除指定文件

D:\workspace_python>mongofiles deletefoo2.txt

2017-01-11T16:36:07.107+0800    connected to: localhost

successfully deleted all instances of'foo2.txt' from GridFS

 

#列表显示所有文件

D:\workspace_python>mongofiles list

2017-01-11T16:36:10.579+0800    connected to: localhost

foo.txt 17

 

 

使用python操作gridFS

示例代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/1/11 17:17
# @Author  : Retacn
# @Site    :  gridFS基本操作
# @File    : gridfs.py
# @Software: PyCharm
__author__ = "retacn"
__copyright__ = "property of mankind."
__license__ = "CN"
__version__ = "0.0.1"
__maintainer__ = "retacn"
__email__ = "zhenhuayue@sina.com"
__status__ = "Development"

from pymongo import MongoClient
import gridfs

client=MongoClient()
db=client.test

fs=gridfs.GridFS(db)
#列表显示gridFS 所有文件
print(fs.list())

#上传文件
file_id=fs.put("hello world!2".encode(),filename="foo2.txt")
print(fs.list())

#下载文件并读取内容
print(fs.get(file_id).read().decode())




 

运行结果如下:

['foo.txt', 'foo2.txt']

['foo.txt', 'foo2.txt']

hello world!2

 

内部原理

gridFS可以将大文件分成多块,每块可以作为单独文档存储

 

#取得不重复的文件名列表

 

服务器端角本

服务器端可以通过db.eval执行javascript脚本

> db.eval("return 1;")

WARNING: db.eval is deprecated

#3.*以上好像不建议使用

 

 

数据库的引用

DBRef,是一个内嵌文档

一个简单的例子:

#使用以下语句可以标识数据库内的任何一个文档

{“$ref”:collection,”$id”:id_value}

 

#如果是引用另一个数据库中的文档

{“$ref”:collection,”$id”:id_value,”$db”:database}

 

简单示列,代码如下:

 

#所有用户信息

> db.users.find()

{ "_id" :ObjectId("586b40507dfc144b68de4071"), "relationships" : {"enemies" : 2, "friend" : 32 }, "username" :"retacn yue", "age" : 33, "sex" : "ma

le", "location" :"ZiBo", "emails" : [ "zhenhuayue@hotmail.com","zhenhuayue@163.com", "zhenhuayue@soho.com","zhenhuayue@126.com" ], "state" : null,

"languages" : [ "java","python", "c", "c++" ] }

{ "_id" :ObjectId("58708a439193775a5f6b5f14"), "username" :"ann", "age" : 30, "sex" : "female","location" : "BoShan", "relationships" : {"enemies"

 : 1,"friend" : 20 }, "emails" : [ "znn@163.com","ann@sina.com" ], "state" : "T","languages" : [ "java", "python", "c++"] }

{ "_id" :ObjectId("58708aeb9193775a5f6b5f16"), "username" :"mike", "age" : 15, "sex" : "male","location" : "HuanTai", "relationships" : {"enemies"

 : 3,"friend" : 18 }, "emails" : [ "mike@163.com","mike@sina.com" ], "state" : "F","languages" : [ "java", "c++" ] }

{ "_id" : ObjectId("58708e5e9193775a5f6b5f18"),"username" : "andy", "age" : 18, "sex": "female", "location" : "ZhangDian","relationships" : { "enem

ies" : 2, "friend" : 15 },"emails" : [ "andy@163.com", "andy@sina.com" ],"state" : "T", "languages" : [ "java","c", "c++" ] }

{ "_id" :ObjectId("5871d6cbc1be409ee45a7899"), "username" :"retacn yue" }

 

 

#添加日记信息

>db.notes.insert({"author":"mike","text":"MongoDBis fun!"})

>db.notes.insert({"author":"andy","text":"and DBRef areeasy,too","references":[{"$ref":"users","$id":"58708aeb9193775a5f6b5f16"},{"$ref":"notes","$

id":"5876fc45ca7f92d67a4482b6"}]})

 

#查询所有日记信息

> db.notes.find()

{ "_id" :ObjectId("5876fc45ca7f92d67a4482b6"), "author" :"mike", "text" : "MongoDB is fun!" }

{ "_id" :ObjectId("5876fdc0ca7f92d67a4482b8"), "author" :"andy", "text" : " and DBRef are easy,too","references" : [ DBRef("users", "58708aeb919377

5a5f6b5f16"), DBRef("notes","5876fc45ca7f92d67a4482b6") ] }

 

#查询第二条笔记对其他文档的引用,以下可以得到用户mike和笔记”MongoDBis fun”

#$ref就是两个文档的集合,$id可以取得”_id”的值

> var note=db.notes.findOne({"_id":ObjectId("5876ff4fca7f92d67a4482b9")});

> note.references.forEach(function(ref){printjson(db[ref.$ref].findOne({"_id":ref.$id})); });

{

       "_id" : ObjectId("58708aeb9193775a5f6b5f16"),

       "username" : "mike",

       "age" : 15,

       "sex" : "male",

       "location" : "HuanTai",

       "relationships" : {

                "enemies" : 3,

                "friend" : 18

       },

       "emails" : [

                "mike@163.com",

                "mike@sina.com"

       ],

       "state" : "F",

       "languages" : [

                "java",

                "c++"

       ]

}

{

       "_id" : ObjectId("5876fc45ca7f92d67a4482b6"),

       "author" : "mike",

       "text" : "MongoDB is fun!"

}

 

使用python实现以上功能

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/1/12 12:13
# @Author  : Retacn
# @Site    : 数据库引用DBRef
# @File    : mongodb_DBRef.py
# @Software: PyCharm
__author__ = "retacn"
__copyright__ = "property of mankind."
__license__ = "CN"
__version__ = "0.0.1"
__maintainer__ = "retacn"
__email__ = "zhenhuayue@sina.com"
__status__ = "Development"

from pymongo import MongoClient
from bson.dbref import DBRef
from bson.objectid import ObjectId

client = MongoClient()
db = client.test

note = {"author": "andy", "text": "and DBRefs are easy,too",
        "references": [DBRef("users", ObjectId("58708aeb9193775a5f6b5f16")),
                       DBRef("notes", ObjectId("5876fc45ca7f92d67a4482b6"))]}

# db.notes.insert(note)

# 查询添加信息
db_note = db.notes.find_one({"_id": ObjectId("587708852e29db1d60e6ad8d")})
#查询记录中引用的文档内容
for dbf in db_note["references"]:
    print(db[dbf.collection].find_one({"_id": dbf.id}))

 

运行结果如下:

{'relationships': {'friend': 18.0,'enemies': 3.0}, 'emails': ['mike@163.com', 'mike@sina.com'], 'languages':['java', 'c++'], 'username': 'mike', 'sex': 'male', '_id':ObjectId('58708aeb9193775a5f6b5f16'), 'age': 15.0, 'location': 'HuanTai','state': 'F'}

{'_id':ObjectId('5876fc45ca7f92d67a4482b6'), 'text': 'MongoDB is fun!', 'author':'mike'}

 

文档中不推荐使用dbrefs

可以直接保存对象的_id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值