首页 > 代码库 > mongodb 入门

mongodb 入门

// 登录
D:\mongodb>D:\mongodb\mongodb206\mongodb206\bin\mongo 127.0.0.1:27017/admin
MongoDB shell version: 2.0.6
connecting to: 127.0.0.1:27017/admin
//在缓存中创建一个数据库 
> use foobar
switched to db foobar
> db.persons.insert(name:"tomcat")
//插入数据后数据库会真正创建
Sat Jun 03 15:22:26 SyntaxError: missing ) after argument list (shell):1
> db.persons.insert((name:"tomcat"))
Sat Jun 03 15:22:41 SyntaxError: missing ) in parenthetical (shell):1
> db.persons.insert({name:"tomcat"})
> show dbs;
//显示所有的数据
foobar  0.03125GB
local   (empty)//默认建立的
> show collections //显示数据库下面的表
persons
system.indexes
> db.system.indexes.fin()
Sat Jun 03 15:24:23 TypeError: db.system.indexes.fin is not a function (shell):1

> db.system.indexes.find(); //查询语句
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "foobar.persons", "name" : "_id_" }
> db.foobar.find();
> db.person.find();
> db.persons.find();//查询所有
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat" }
> db.persons.findone(); //查询第一条
Sat Jun 03 15:27:20 TypeError: db.persons.findone is not a function (shell):1
> db.persons.insert({name:"extjs"})//新增数据
> db.persons.find();
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat" }
{ "_id" : ObjectId("593264f2622897d4e7c9b221"), "name" : "extjs" }
//更新数据,第一个参数是选择器,第二个是要更新的数据
> db.persons.update({name:"extjs"},{$set:{name:"extjs4.0"}});

> db.persons.find();
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat" }
{ "_id" : ObjectId("593264f2622897d4e7c9b221"), "name" : "extjs4.0" }
> var p  = db.persons.findOne(); //定义变量
> p //查看
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat" }
> db.persons.update(p,{$set:{name:"tomcat8"}});
> db.persons.find(); //查找
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat8" }
{ "_id" : ObjectId("593264f2622897d4e7c9b221"), "name" : "extjs4.0" }
> p
{ "_id" : ObjectId("593263d9622897d4e7c9b220"), "name" : "tomcat" }
> var p  = db.persons.findOne();
> db.persons.update(p,{$set:{name:"tomcat8",age=1}});
Sat Jun 03 15:40:08 SyntaxError: missing : after property id (shell):1
> db.persons.update(p,{$set:{name:"tomcat8",age="1"}});
Sat Jun 03 15:40:22 SyntaxError: missing : after property id (shell):1
> db.persons.update(p,{$set:{name:"tomcat8",age:"1"}});
//删除操作表
> db.persons.remove({age:"1"})
> db.persons.find()
{ "_id" : ObjectId("593264f2622897d4e7c9b221"), "name" : "extjs4.0" }
> show collections
persons
system.indexes
//删除当前数据库
> db.dropDatabases()
Sat Jun 03 15:47:16 TypeError: db.dropDatabases is not a function (shell):1
> show dbs //显示所有的数据库
foobar  0.03125GB
local   (empty)
> db.dropDatabase()
{ "dropped" : "foobar", "ok" : 1 }
> show  dbs;
local   (empty)
> use foobar
switched to db foobar
> db.persons.insert({age:1,name:"tom",gender:"1"})
> db.persons.find();
{ "_id" : ObjectId("593269f2622897d4e7c9b222"), "age" : 1, "name" : "tom", "gend
er" : "1" }
> show dbs;
foobar  0.03125GB
local   (empty)
> show collections;
persons
system.indexes
> db.help() //帮助
DB methods:
        db.addUser(username, password[, readOnly=false])
        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.currentOp() displays the current operation in the db
        db.dropDatabase()
        db.eval(func, args) run code server-side
        db.getCollection(cname) same as db[cname] or db.cname
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow this connection to read from the nonmas
ter member of a replica pair
        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.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printSlaveReplicationInfo()
        db.printShardingStatus()
        db.removeUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, tu
rns it into { cmdObj : 1 }
        db.serverStatus()
        db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
        db.shutdownServer()
        db.stats()
        db.version() current version of the server
        db.getMongo().setSlaveOk() allow queries on a replication slave server
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnock() unlocks server following a db.fsyncLock()
> db.dbgetName()
Sat Jun 03 16:03:03 TypeError: db.dbgetName is not a function (shell):1
> db.dbgetName()
Sat Jun 03 16:03:11 TypeError: db.dbgetName is not a function (shell):1
> db.getName()//获取当前是数据库名字
foobar
> db.getstatus
foobar.getstatus
> db.status()
Sat Jun 03 16:03:39 TypeError: db.status is not a function (shell):1
> db.stats()  //获取当前数据库的信息
{
        "db" : "foobar",
        "collections" : 3,
        "objects" : 5,
        "avgObjSize" : 48.8,
        "dataSize" : 244,
        "storageSize" : 12288,
        "numExtents" : 3,
        "indexes" : 1,
        "indexSize" : 8176,
        "fileSize" : 16777216,
        "nsSizeMB" : 16,
        "ok" : 1
}
> db.persons.count() 
1
> db.person.help();//帮助
DBCollection help
        db.person.find().help() - show DBCursor help
        db.person.count()
        db.person.dataSize()
        db.person.distinct( key ) - eg. db.person.distinct( x )
        db.person.drop() drop the collection
        db.person.dropIndex(name)
        db.person.dropIndexes()
        db.person.ensureIndex(keypattern[,options]) - options is an object with
these possible fields: name, unique, dropDups
        db.person.reIndex()
        db.person.find([query],[fields]) - query is an optional query filter. fi
elds is optional set of fields to return.
                                                      e.g. db.person.find( {x:77
} , {name:1, x:1} )
        db.person.find(...).count()
        db.person.find(...).limit(n)
        db.person.find(...).skip(n)
        db.person.find(...).sort(...)
        db.person.findOne([query])
        db.person.findAndModify( { update : ... , remove : bool [, query: {}, so
rt: {}, new: false] } )
        db.person.getDB() get DB object associated with collection
        db.person.getIndexes()
        db.person.group( { key : ..., initial: ..., reduce : ...[, cond: ...] }
)
        db.person.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.person.remove(query)
        db.person.renameCollection( newName , <dropTarget> ) renames the collect
ion.
        db.person.runCommand( name , <options> ) runs a db command with the give
n name where the first param is the collection name
        db.person.save(obj)
        db.person.stats()
        db.person.storageSize() - includes free space allocated to this collecti
on
        db.person.totalIndexSize() - size in bytes of all the indexes
        db.person.totalSize() - storage allocated for all data and indexes
        db.person.update(query, object[, upsert_bool, multi_bool])
        db.person.validate( <full> ) - SLOW
        db.person.getShardVersion() - only for use with sharding
        db.person.getShardDistribution() - prints statistics about data distribu
tion in the cluster
定义一个函数,函数的功能是插入数据
> function insert3(o){ db.getCollection("persons").insert(o);
... }
> insert3({name:"kitty"})
> db.persons.find();
{ "_id" : ObjectId("593269f2622897d4e7c9b222"), "age" : 1, "name" : "tom", "gend
er" : "1" }
{ "_id" : ObjectId("5932733d622897d4e7c9b227"), "name" : "kitty" }
>
//将参数中的字符串当做js代码处理

> db.eval(‘return "hello mongodb "‘);
hello mongodb

> for (var i = 0; i<10 ;i++){ db.persons.insert({name:i})
... }
> db.persons.find()
{ "_id" : ObjectId("593269f2622897d4e7c9b222"), "age" : 1, "name" : "tom", "gend
er" : "1" }
{ "_id" : ObjectId("5932733d622897d4e7c9b227"), "name" : "kitty" }
{ "_id" : "0001", "name" : "yarn" }
{ "_id" : ObjectId("59327d6e622897d4e7c9b228"), "name" : 0 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b229"), "name" : 1 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22a"), "name" : 2 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22b"), "name" : 3 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22c"), "name" : 4 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22d"), "name" : 5 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22e"), "name" : 6 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b22f"), "name" : 7 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b230"), "name" : 8 }
{ "_id" : ObjectId("59327d6e622897d4e7c9b231"), "name" : 9 }

save和insert的区别,save会变成更新语句并保存,insert则会报错

删除所有,但是索引不会删除
> db.persons.remove() > db.persons.find()

> db.persons.update({_id:"02"}, {_id:"02",name:"x0023"},true);//insert or update
> db.persons.find()
{ "_id" : "01", "name" : "01" }
{ "_id" : "02", "name" : "x0023" }
{ "_id" : "03", "name" : "x03" }

 

批量新增 在shell中是通过循环实现的,

更新时,只会更新满足条件的第一条数据

批量更新

> db.persons.update({name:"x03"}, {$set:{name:"x03sd"}},false,true);//批量更新
> db.persons.find()
{ "_id" : "01", "name" : "01" }
{ "_id" : "02", "name" : "x03sd" }
{ "_id" : "03", "name" : "x03sd" }
>

 

mongodb 入门