mongoDB学习笔记一

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 15:23   11   0

第二章入门

Windows上安装mongoDB

下载地址:https://www.mongodb.org/downloads

双击安装-->next-->next-->custom-->设置安装目录(h:\MongoDB\)

运行mongonDB,根目录下创建\data\db目录

Cmd 进入安装根目录,执行如下命令

mongod.exe --dbpath h:\MongoDB\data

出现如下错误:

exception in initAndListen: 28663 Cannotstart server. The default is notavailable with this build of mongod. Please specify a different storage engineexplicitly, e.g. --storageEngine=mma

执行如下命令:

mongod.exe --dbpath h:\MongoDB\data --storageEngine=mmapv1

看到如下结果:

H:\MongoDB\Server\3.2\bin>mongod.exe--dbpath h:\MongoDB\data --storageEngine=mmapv1

2016-11-20T09:08:10.655+0800 I CONTROL [main]

2016-11-20T09:08:10.655+0800 W CONTROL [main] 32-bit servers don't have journalingenabled by default. Please use --journal if you want durability.

2016-11-20T09:08:10.655+0800 I CONTROL [main]

2016-11-20T09:08:10.671+0800 I CONTROL [main] Hotfix KB2731284 or later update isnot installed, will zero-out data files

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] MongoDB starting : pid=6232port=27017 dbpath=h:\MongoDB\data 32-bit host=retacn

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] targetMinOS: WindowsVista/Windows Server 2008

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] db version v3.2.10

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] git version:79d9b3ab5ce20f51c272b4411202710a082d0317

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] allocator: tcmalloc

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] modules: none

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] build environment:

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] distarch: i386

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] target_arch: i386

2016-11-20T09:08:10.671+0800 I CONTROL [initandlisten] options: { storage: { dbPath:"h:\MongoDB\data", engine: "mmapv1" } }

2016-11-20T09:08:10.777+0800 I CONTROL [initandlisten]

2016-11-20T09:08:10.777+0800 I CONTROL [initandlisten] ** WARNING: This 32-bitMongoDB binary is deprecated

2016-11-20T09:08:10.778+0800 I CONTROL [initandlisten] ** NOTE: This is a 32-bitMongoDB binary running on a 64-bit operating

2016-11-20T09:08:10.778+0800 I CONTROL [initandlisten] ** system. Switch to a 64-bit build ofMongoDB to

2016-11-20T09:08:10.779+0800 I CONTROL [initandlisten] ** support larger databases.

2016-11-20T09:08:10.779+0800 I CONTROL [initandlisten]

2016-11-20T09:08:10.779+0800 I CONTROL [initandlisten]

2016-11-20T09:08:10.780+0800 I CONTROL [initandlisten] ** NOTE: This is a 32 bitMongoDB binary.

2016-11-20T09:08:10.780+0800 I CONTROL [initandlisten] ** 32 bit builds are limited to less than2GB of data (or less with --journal).

2016-11-20T09:08:10.780+0800 I CONTROL [initandlisten] ** Note that journaling defaults to off for32 bit and is currently off.

2016-11-20T09:08:10.782+0800 I CONTROL [initandlisten] ** See http://dochub.mongodb.org/core/32bit

2016-11-20T09:08:10.784+0800 I CONTROL [initandlisten]

2016-11-20T09:08:10.790+0800 I INDEX [initandlisten] allocating new ns fileh:\MongoDB\data\local.ns, filling with zeroes...

2016-11-20T09:08:11.211+0800 I STORAGE [FileAllocator] allocating new datafileh:\MongoDB\data\local.0, filling with zeroes...

2016-11-20T09:08:11.213+0800 I STORAGE [FileAllocator] creating directoryh:\MongoDB\data\_tmp

2016-11-20T09:08:11.573+0800 I STORAGE [FileAllocator] done allocating datafileh:\MongoDB\data\local.0, size: 64MB,took 0.356 secs

2016-11-20T09:08:11.577+0800 I NETWORK [HostnameCanonicalizationWorker] Startinghostname canonicalization worker

2016-11-20T09:08:11.577+0800 I FTDC [initandlisten] Initializing full-timediagnostic data capture with directory 'h:/MongoDB/data/diagnostic.data

'

2016-11-20T09:08:11.583+0800 I NETWORK [initandlisten] waiting for connections onport 27017

MongoDB的默认使用27017端口

重新启动一个mongoDB,运行mongo.exe

H:\MongoDB\bin>mongo.exe

2016-11-20T09:31:58.985+0800 I CONTROL [main] Hotfix KB2731284 or later update isnot installed, will zero-out data files

MongoDB shell version: 3.2.11

connecting to: test

#插入两件记录

> db.foo.insert({test:1})

WriteResult({ "nInserted" : 1 })

> db.foo.insert({test:2})

WriteResult({ "nInserted" : 1 })

#查询记录

> db.foo.find()

{ "_id" :ObjectId("5830fd65465a96c3b983ef1d"), "test" : 1 }

{ "_id" :ObjectId("5830fd6d465a96c3b983ef1e"), "test" : 2 }

#移除一条记录

> db.foo.remove({test:1})

WriteResult({ "nRemoved" : 1 })

#查询记录

> db.foo.find()

{ "_id" : ObjectId("5830fd6d465a96c3b983ef1e"),"test" : 2 }

创建mongoDB服务

方法一:

Cmd-->ctrl+shiift+enter(以管理员身份运行)

创建数据和日志服务

创建配置文件

H:\MongoDB>mkdir h:\MongoDB\data\db

H:\MongoDB>mkdir h:\MongoDB\data\log

创建配置文件

根目录下创建mongod.cfg文件,添加如下内容:

systemLog:

destination: file

path: H:\MongoDB\data\log\mongod.txt

storage:

dbPath: H:\MongoDB\data\db

安装服务

mongod.exe --config h:\MongoDB\mongod.cfg--install --serviceName MongoDB

第二种方法

sc.exe create MongoDB binPath="\"h:\MongoDB\bin\mongod.exe\" --service --config=\"h:\MongoDB\mongod.cfg\""DisplayName= "MongoDB" start= "auto"

开启服务

Net start MondoDB

关闭服务

Net stop MonDB

删除服务

方式一:

mongod.exe--remove

方式二:

sc.exe delete MongoDB

运行shell:

#启动时会自运连接mongodb服务器

C:\Users\Administrator>mongo.exe

2017-01-02T21:52:17.980+0800 I CONTROL [main] Hotfix KB2731284 or later update isnot installed, will zero-out data files

MongoDB shell version: 3.2.11

connecting to: test

#shell具备功能完备的javascript解释器,可以运行javascript程序

> Math.sin(Math.PI/2);

1

> new Date("2017/1/1");

ISODate("2016-12-31T16:00:00Z")

> "HelloWorld!".replace("World","MongoDB");

Hello MongoDB!

#查看当前指向数据库

> db

Test

#重新指向数据库

> use foobar

switched to db foobar

> db

Foobar

#创建,添加一个文档到集合中

> post={"title":"My Blogpost","content":"Here is my bolgpost.","data":new Date()}

{

"title" : "My Blog post",

"content" : "Here is my bolg post.",

"data" : ISODate("2017-01-02T14:17:53.878Z")

}

#读取

#查询所有文档,最多显示20条

> db.blog.find()

{ "_id" :ObjectId("586a617718af40bbf39030b0"), "title" : "MyBlog post", "content" : "Here is my bolg post.","data" : ISODate("2017-01-02T14:17:53.8

78Z") }

#只查看一条记录

> db.blog.findOne()

{

"_id" : ObjectId("586a617718af40bbf39030b0"),

"title" : "My Blog post",

"content" : "Here is my bolg post.",

"data" : ISODate("2017-01-02T14:17:53.878Z")

}

>

#更新

#1添加新字段

> post.comments=[]

[ ]

> db.blog.update({title:"My Blogpost"},post)

WriteResult({ "nMatched" : 1,"nUpserted" : 0, "nModified" : 1 })

> db.bolg.find()

> db.blog.findOne()

{

"_id" : ObjectId("586a617718af40bbf39030b0"),

"title" : "My Blog post",

"content" : "Here is my bolg post.",

"data" : ISODate("2017-01-02T14:17:53.878Z"),

"comments" : [ ]

}

#删除

>db.blog.remove({title:"My Blog post"})

WriteResult({"nRemoved" : 1 })

>db.blog.find()

Shell的常用方法:

#查看数据库名

> show dbs

local0.000GB

test0.000GB

#查看当前数据库的集合

> show collections

Foo

#查看用户

> show users

> show profile

db.system.profile is empty

Use db.setProfilingLevel(2) will enableprofiling

Use db.system.profile.find() to show rawprofile entries

> db.help()

DB methods:

db.adminCommand(nameOrDocument) - switches to 'admin' db, and runscommand [ just calls db.runCommand(...) ]

db.auth(username, password)

db.cloneDatabase(fromhost)

db.commandHelp(name) returns the help for the command

db.copyDatabase(fromdb, todb, fromhost)

db.createCollection(name, { size : ..., capped : ..., max : ... } )

db.createUser(userDocument)

db.currentOp() displays currently executing operations in the db

db.dropDatabase()

db.eval() - deprecated

db.fsyncLock() flush data to disk and lock server for backups

db.fsyncUnlock() unlocks server following a db.fsyncLock()

db.getCollection(cname) same as db['cname'] or db.cname

db.getCollectionInfos([filter]) - returns a list that contains the namesand options of the db's collections

db.getCollectionNames()

db.getLastError() - just returns the err msg string

db.getLastErrorObj() - return full status object

db.getLogComponents()

db.getMongo() get the server connection object

db.getMongo().setSlaveOk() allow queries on a replication slave server

db.getName()

db.getPrevError()

db.getProfilingLevel() - deprecated

db.getProfilingStatus() - returns if profiling is on and slow threshold

db.getReplicationInfo()

db.getSiblingDB(name) get the db at the same server as this one

db.getWriteConcern() - returns the write concern used for any operationson this db, inherited from server object if set

db.hostInfo() get details about the server's host

db.isMaster() check replica primary status

db.killOp(opid) kills the current operation in the db

db.listCommands() lists all the db commands

db.loadServerScripts() loads all the scripts in db.system.js

db.logout()

db.printCollectionStats()

db.printReplicationInfo()

db.printShardingStatus()

db.printSlaveReplicationInfo()

db.dropUser(username)

db.repairDatabase()

db.resetError()

db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj: 1 }

db.serverStatus()

db.setLogLevel(level,<component>)

db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all

db.setWriteConcern( <write concern doc> ) - sets the write concernfor writes to the db

db.unsetWriteConcern( <write concern doc> ) - unsets the writeconcern for writes to the db

db.setVerboseShell(flag) display extra information in shell output

db.shutdownServer()

db.stats()

db.version() current version of the server

> db.foo.help()

DBCollection help

db.foo.find().help() - show DBCursor help

db.foo.bulkWrite( operations, <optional params> ) - bulk executewrite operations, optional parameters are: w, wtimeout, j

db.foo.count( query = {}, <optional params> ) - count the numberof documents that matches the query, optional parameters are: limit, skip, hi

nt, maxTimeMS

db.foo.copyTo(newColl) - duplicates collection by copying all documentsto newColl; no indexes are copied.

db.foo.convertToCapped(maxBytes) - calls {convertToCapped:'foo',size:maxBytes}} command

db.foo.createIndex(keypattern[,options])

db.foo.createIndexes([keypatterns], <options>)

db.foo.dataSize()

db.foo.deleteOne( filter, <optional params> ) - delete firstmatching document, optional parameters are: w, wtimeout, j

db.foo.deleteMany( filter, <optional params> ) - delete allmatching documents, optional parameters are: w, wtimeout, j

db.foo.distinct( key, query, <optional params> ) - e.g.db.foo.distinct( 'x' ), optional parameters are: maxTimeMS

db.foo.drop() drop the collection

db.foo.dropIndex(index) - e.g. db.foo.dropIndex( "indexName" )or db.foo.dropIndex( { "indexKey" : 1 } )

db.foo.dropIndexes()

db.foo.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex()instead

db.foo.explain().help() - show explain help

db.foo.reIndex()

db.foo.find([query],[fields]) - query is an optional query filter.fields is optional set of fields to return.

e.g. db.foo.find( {x:77} , {name:1, x:1} )

db.foo.find(...).count()

db.foo.find(...).limit(n)

db.foo.find(...).skip(n)

db.foo.find(...).sort(...)

db.foo.findOne([query], [fields], [options], [readConcern])

db.foo.findOneAndDelete( filter, <optional params> ) - deletefirst matching document, optional parameters are: projection, sort, maxTimeMS

db.foo.findOneAndReplace( filter, replacement, <optional params> )- replace first matching document, optional parameters are: projection, sor

t, maxTimeMS, upsert, returnNewDocument

db.foo.findOneAndUpdate( filter, update, <optional params> ) -update first matching document, optional parameters are: projection, sort, maxT

imeMS, upsert, returnNewDocument

db.foo.getDB() get DB object associated with collection

db.foo.getPlanCache() get query plan cache associated with collection

db.foo.getIndexes()

db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )

db.foo.insert(obj)

db.foo.insertOne( obj, <optional params> ) - insert a document,optional parameters are: w, wtimeout, j

db.foo.insertMany( [objects], <optionalparams> ) - insert multiple documents, optional parameters are: w, wtimeout,j

db.foo.mapReduce( mapFunction , reduceFunction , <optional params>)

db.foo.aggregate( [pipeline], <optional params> ) - performs anaggregation on a collection; returns a cursor

db.foo.remove(query)

db.foo.replaceOne( filter, replacement, <optional params> ) -replace the first matching document, optional parameters are: upsert, w,wtimeou

t, j

db.foo.renameCollection( newName , <dropTarget> ) renames thecollection.

db.foo.runCommand( name , <options> ) runs a db command with thegiven name where the first param is the collection name

db.foo.save(obj)

db.foo.stats({scale: N, indexDetails: true/false, indexDetailsKey:<index key>, indexDetailsName: <index name>})

db.foo.storageSize() - includes free space allocated to this collection

db.foo.totalIndexSize() - size in bytes of all the indexes

db.foo.totalSize() - storage allocated for all data and indexes

db.foo.update( query, object[, upsert_bool, multi_bool] ) - instead oftwo flags, you can pass an object with fields: upsert, multi

db.foo.updateOne( filter, update, <optional params> ) - update thefirst matching document, optional parameters are: upsert, w, wtimeout, j

db.foo.updateMany( filter, update, <optional params> ) - updateall matching documents, optional parameters are: upsert, w, wtimeout, j

db.foo.validate( <full> ) - SLOW

db.foo.getShardVersion() - only for use with sharding

db.foo.getShardDistribution() - prints statistics about datadistribution in the cluster

db.foo.getSplitKeysForChunks( <maxChunkSize> ) - calculates splitpoints over all chunks and returns splitter function

db.foo.getWriteConcern() - returns the write concern used for anyoperations on this collection, inherited from server/db if set

db.foo.setWriteConcern( <write concern doc> ) - sets the writeconcern for writes to the collection

db.foo.unsetWriteConcern( <write concern doc> ) - unsets the writeconcern for writes to the collection

#查询集合中的所有对象

> db.foo.find()

{ "_id" :ObjectId("586a5b4118af40bbf39030af"), "test" : 2 }

> db.foo.find({test:1})

#查询指定对像

> db.foo.find({test:2})

{ "_id" :ObjectId("586a5b4118af40bbf39030af"), "test" : 2 }

>

6 数据类型

null

布尔

32位整数

64位整数

64位浮点数

字符串

符号

对象id

日期

正则表达式

代码

二进制数据

最大值

最小值

未定义

数组

内嵌文档
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP