Mongodb操作详解

来源:互联网 发布:情报大数据分析平台 编辑:程序博客网 时间:2024/05/17 20:14
Mongodb操作详解
C:\Users\Administrator>F:

F:\>cd Mongodb206

F:\Mongodb206>cd bin

F:\Mongodb206\bin>mongo.exe
MongoDB shell version: 2.0.6
connecting to: test
> show dbs;   //显示所有的数据库,相当于mysql的show databases;
local   (empty) //只有一个local数据库(无表)
> use local     //选择local数据库
switched to db local
> show tables;   //show tables
>                //无表显示
> post = {"title":"My Blog Post",
... "content":"Here's my blog post.",
... "created":new Date()}  
//post字典变量,是javascript语句,如new Date()
//其实shell运行环境支持javascript语言,
{
        "title" : "My Blog Post",
        "content" : "Here's my blog post.",
        "created" : ISODate("2012-08-11T11:38:08.698Z")
}
> db.blog.insert(post)     
//把post数据输入local数据库中blog(数据库中
//不存在就自动建立)集合(即表)中
> db.blog.find()     //将blog中数据全部找出,相当与select * from blog;
{ "_id" : ObjectId("502644352d31a25926fc6e85"), "title" : "My Blog Post", "conte
nt" : "Here's my blog post.", "created" : ISODate("2012-08-11T11:38:08.698Z") }
>db.blog.findOne()  //只查找集合(表)中一个文档(行)数据
{ "_id" : ObjectId("502644352d31a25926fc6e85"), "title" : "My Blog Post", "conte
nt" : "Here's my blog post.", "created" : ISODate("2012-08-11T11:38:08.698Z") }
更新 update
> post.comments=[]     //给之前的那个post字典变量添加一个comments键值
[ ]
> db.blog.update({title:"My Blog Post"},post)  
//update()至少接受两个参数,第一个为限制条件,第二个为更改内容
//执行这个后,原文档(行)添加一个字段comments值为空。
> db.blog.find()
{ "_id" : ObjectId("502644352d31a25926fc6e85"), "title" : "My Blog Post", "conte
nt" : "Here's my blog post.", "created" : ISODate("2012-08-11T11:38:08.698Z"), "
comments" : [ ] }
>
删除 remove delete
> db.blog.remove({title:"My Blog Post"})
//删除title为这个的一文档(行)数据

帮助 help
> help     //查询mongo的javascript shell的帮助
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        rs.help()                    help on replica set methods
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries wit
h time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memor
y, 'global' is default
        use <db_name>                set current database
        db.foo.find()                list objects in collection foo
        db.foo.find( { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to f
urther iterate
        DBQuery.shellBatchSize = x   set default number of items to display on s
hell
        exit                         quit the mongo shell

> 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.foo.help()           //查询集合(表)级别的帮助
DBCollection help
        db.foo.find().help() - show DBCursor help
        db.foo.count()
        db.foo.dataSize()
        db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )
        db.foo.drop() drop the collection
        db.foo.dropIndex(name)
        db.foo.dropIndexes()
        db.foo.ensureIndex(keypattern[,options]) - options is an object with the
se possible fields: name, unique, dropDups
        db.foo.reIndex()
        db.foo.find([query],[fields]) - query is an optional query filter. field
s 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])
        db.foo.findAndModify( { update : ... , remove : bool [, query: {}, sort:
 {}, 'new': false] } )
        db.foo.getDB() get DB object associated with collection
        db.foo.getIndexes()
        db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
        db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.foo.remove(query)
        db.foo.renameCollection( newName , <dropTarget> ) renames the collection
.
        db.foo.runCommand( name , <options> ) runs a db command with the given n
ame where the first param is the collection name
        db.foo.save(obj)
        db.foo.stats()
        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])
        db.foo.validate( <full> ) - SLOW
        db.foo.getShardVersion() - only for use with sharding
        db.foo.getShardDistribution() - prints statistics about data distributio
n in the cluster
>

//想要了解一个函数,可以不写括号()运行,即可打印出该函数的源代码
> db.foo.update  
function (query, obj, upsert, multi) {
    assert(query, "need a query");
    assert(obj, "need an object");
    var firstKey = null;
    for (var k in obj) {
        firstKey = k;
        break;
    }
    if (firstKey != null && firstKey[0] == "$") {
        this._validateObject(obj);
    } else {
        this._validateForStorage(obj);
    }
    this._mongo.update(this._fullName, query, obj, upsert ? true : false, multi
? true : false);
}

//当集合(表)和db原有的属性相同时
//如db.version()为得到版本的函数
//当你创建集合(表)时,创建了同名的时
//那运行db.version得到的时version()函数源代码
//办法是运行db.getCollection('version')

更多待续。。。。。。。