学习笔记——MongDB非关系型数据库的脚本代码汇总

#打开服务器(可以做成一个.bat文件,将命令写入其中,之后直接单击该文件就可以运行了)
#命令如下所示:
mongod  --dbpath   H:\MongoDB\MongoDBDATA209


#打开客户端
#命令如下所示
mongo 127.0.0.1:27017/admin


#mongodb插入命令
>db .persons.insert({name:"uspcat"})


#显示数据库命令
>show dbs
foobar  0.078125GB
local   (empty)


#进入一个数据库(如果数据名字不存在就创建一个数据库)
> use foobar
switched to db foobar


#插入一条记录
db.persons.insert({name:"guanxiangqing"})


#显示数据表字段名命令(查看数据库中的所有文档)
> show collections
persons
system.indexes


#查看system.indexes字段的详细信息
> db.system.indexes.find()
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "foodar.persons", "name" : "_id_" }


#查看persons字段详细信息
> db.persons.find()
{ "_id" : ObjectId("531a859beaba916f872706ef"), "name" : "guanxiangqing" }


#继续插入一条信息
> db.persons.insert({name:"uspcat"})
> db.persons.find()
{ "_id" : ObjectId("531a859beaba916f872706ef"), "name" : "guanxiangqing" }
{ "_id" : ObjectId("531a86a1eaba916f872706f0"), "name" : "uspcat" }


#mongodb修改(更新)数据命令
>db.persons.update({name:"uspcat"},{$set:{name:"extjs4.1"}})
> db.persons.find()
{ "_id" : ObjectId("531a859beaba916f872706ef"), "name" : "guanxiangqing" }
{ "_id" : ObjectId("531a86a1eaba916f872706f0"), "name" : "extjs4.1" }


#mongodb删除数据命令
> db.persons.find()
{ "_id" : ObjectId("531a859beaba916f872706ef"), "name" : "guanxiangqing" }
{ "_id" : ObjectId("531a86a1eaba916f872706f0"), "name" : "extjs4.1" }
> db.persons.remove({name:"extjs4.1"})
> db.persons.find()
{ "_id" : ObjectId("531a859beaba916f872706ef"), "name" : "guanxiangqing" }


#db.help相关的文档命令,参看所有的参数
> db.help
function () {
    print("DB methods:");
    print("\tdb.addUser(username, password[, readOnly=false])");
    print("\tdb.auth(username, password)");
    print("\tdb.cloneDatabase(fromhost)");
    print("\tdb.commandHelp(name) returns the help for the command");
    print("\tdb.copyDatabase(fromdb, todb, fromhost)");
    print("\tdb.createCollection(name, { size : ..., capped : ..., max : ... } )
");
    print("\tdb.currentOp() displays the current operation in the db");
    print("\tdb.dropDatabase()");
    print("\tdb.eval(func, args) run code server-side");
    print("\tdb.getCollection(cname) same as db['cname'] or db.cname");
    print("\tdb.getCollectionNames()");
    print("\tdb.getLastError() - just returns the err msg string");
    print("\tdb.getLastErrorObj() - return full status object");
    print("\tdb.getMongo() get the server connection object");
    print("\tdb.getMongo().setSlaveOk() allow this connection to read from the n
onmaster member of a replica pair");
    print("\tdb.getName()");
    print("\tdb.getPrevError()");
    print("\tdb.getProfilingLevel() - deprecated");
    print("\tdb.getProfilingStatus() - returns if profiling is on and slow thres
hold ");
    print("\tdb.getReplicationInfo()");
    print("\tdb.getSiblingDB(name) get the db at the same server as this one");
    print("\tdb.isMaster() check replica primary status");
    print("\tdb.killOp(opid) kills the current operation in the db");
    print("\tdb.listCommands() lists all the db commands");
    print("\tdb.logout()");
    print("\tdb.printCollectionStats()");
    print("\tdb.printReplicationInfo()");
    print("\tdb.printSlaveReplicationInfo()");
    print("\tdb.printShardingStatus()");
    print("\tdb.removeUser(username)");
    print("\tdb.repairDatabase()");
    print("\tdb.resetError()");
    print("\tdb.runCommand(cmdObj) run a database command.  if cmdObj is a strin
g, turns it into { cmdObj : 1 }");
    print("\tdb.serverStatus()");
    print("\tdb.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all");
    print("\tdb.shutdownServer()");
    print("\tdb.stats()");
    print("\tdb.version() current version of the server");
    print("\tdb.getMongo().setSlaveOk() allow queries on a replication slave ser
ver");
    print("\tdb.fsyncLock() flush data to disk and lock server for backups");
    print("\tdb.fsyncUnock() unlocks server following a db.fsyncLock()");
    return __magicNoPrint;
}
>


#db.help()查看使用函数
> 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.stats()查看状态
> db.stats()
{
        "db" : "foobar",
        "collections" : 3,
        "objects" : 5,
        "avgObjSize" : 45.6,
        "dataSize" : 228,
        "storageSize" : 12288,
        "numExtents" : 3,
        "indexes" : 1,
        "indexSize" : 8176,
        "fileSize" : 67108864,
        "nsSizeMB" : 16,
        "ok" : 1
}
>


#mongoDB相关的API帮助文档
http://api.mongodb.org/js/2.1.2/index.html




> use db-text
switched to db db-text
> db.getCollection("db-text").text.insert({name:123456})
> db.getCollection("db-text").text.find()
{ "_id" : ObjectId("5319d1616a432841d55ea522"), "name" : 123456 }




> db.getCollection("db-text").text.find()
{ "_id" : ObjectId("5319d1616a432841d55ea522"), "name" : 123456 }
> insert({name:"yun"})
> db.getCollection("db-text").text.find()
{ "_id" : ObjectId("5319d1616a432841d55ea522"), "name" : 123456 }


#自己书写函数,方便以后直接使用(javascript代码,如下所示)
> function insert(object){
... db.getCollection("db-text").text.insert(object)
... }


#调用自己写的函数,插入一条数据命令
> insert({name:"yun"})
> db.getCollection("db-text").text.find()
{ "_id" : ObjectId("5319d1616a432841d55ea522"), "name" : 123456 }
{ "_id" : ObjectId("5319db8e6a432841d55ea525"), "name" : "yun" }
>


#内嵌文档
> insert({name:"uspcat",child:{name:"JS"}})
> db.getCollection("db-text").text.find()
{ "_id" : ObjectId("5319d1616a432841d55ea522"), "name" : 123456 }
{ "_id" : ObjectId("5319db8e6a432841d55ea525"), "name" : "yun" }
{ "_id" : ObjectId("5319dfcf6a432841d55ea526"), "name" : "uspcat", "child" : { "
name" : "JS" } }
>

> db.persons.update({_id:5},{$push:{books:"js"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "js" ], "name" : 5 }
> db.persons.update({_id:5},{$push:{books:"guanxiangqing"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "js", "guanxiangqing" ], "name" : 5 }
> db.persons.update({_id:5},{$push:{classes:"class01"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "js", "guanxiangqing" ], "classes" : [ "class01" ], "na
me" : 5 }
> db.persons.update({_id:5},{$pushAll:{classes:["02","03","04"]}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "js", "guanxiangqing" ], "classes" : [ "class01", "02",
 "03", "04" ], "name" : 5 }
> db.persons.update({_id:5},{$addToSet:{books:"extjs"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "js", "guanxiangqing", "extjs" ], "classes" : [ "class0
1", "02", "03", "04" ], "name" : 5 }
> db.persons.update({_id},{$pop:{books:-1}})
Sat Mar 08 10:21:06 SyntaxError: missing : after property id (shell):1
> db.persons.update({_id:5},{$pop:{books:-1}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing", "extjs" ], "classes" : [ "class01", "0
2", "03", "04" ], "name" : 5 }
> db.persons.update({_id:5},{$pop:{books:1}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ "class01", "02", "03",
 "04" ], "name" : 5 }
> db.persons.update({_id:5},{$pull:{classes:"02"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ "class01", "03", "04"
], "name" : 5 }
> db.persons.update({_id:5},{$pullAll:{classes:["class01","03","04"]}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ ], "name" : 5 }
> :[{type:"js",name:"jquery"},{type:"JS",name:"extjs4"},{type:"DB",name:"mongdb"
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ ], "name" : 5 }
{ "_id" : 6, "books" : [        {       "type" : "js",  "name" : "jquery" },
{       "type" : "JS",  "name" : "extjs4" },    {       "type" : "DB",  "name" :
 "mongdb" } ] }
> db.persons.update({"books.type":"JS"},{$set:{"books.$.author":"uspcat"}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ ], "name" : 5 }
{ "_id" : 6, "books" : [        {       "type" : "js",  "name" : "jquery" },
{       "author" : "uspcat",    "name" : "extjs4",      "type" : "JS" },
{       "type" : "DB",  "name" : "mongdb" } ] }
> db.persons.remove({_id:6})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing" ], "classes" : [ ], "name" : 5 }
> db.persons.update({_id:5},{$addToSet:{books:{$each:["js","DB"]}}})
> db.persons.find()
{ "_id" : ObjectId("53197c896a432841d55ea521"), "name" : "guanxiangqing" }
{ "_id" : "001", "name" : 10 }
{ "_id" : ObjectId("531a73e76a9b55fae97d434f"), "0" : { "name" : "34" }, "1" : {
 "name" : "234" } }
{ "_id" : ObjectId("531a74426a9b55fae97d4350"), "name" : 0 }
{ "_id" : ObjectId("531a74426a9b55fae97d4351"), "name" : 1 }
{ "_id" : ObjectId("531a74426a9b55fae97d4352"), "name" : 2 }
{ "_id" : ObjectId("531a74426a9b55fae97d4353"), "name" : "nihao" }
{ "_id" : ObjectId("531a74426a9b55fae97d4354"), "name" : 4 }
{ "_id" : ObjectId("531a74426a9b55fae97d4355"), "name" : 5 }
{ "_id" : ObjectId("531a74426a9b55fae97d4356"), "name" : 6 }
{ "_id" : ObjectId("531a74426a9b55fae97d4357"), "name" : 7 }
{ "_id" : ObjectId("531a74426a9b55fae97d4358"), "name" : 8 }
{ "_id" : ObjectId("531a74426a9b55fae97d4359"), "name" : 9 }
{ "_id" : 1, "name" : 1 }
{ "_id" : 2, "name" : 2 }
{ "_id" : 3, "name" : "nihao" }
{ "_id" : 4, "name" : 4 }
{ "_id" : 5, "books" : [ "guanxiangqing", "js", "DB" ], "classes" : [ ], "name"
: 5 }
>

#第三周的的脚本源代码(详细记录)


H:\MongoDB>mongo 127.0.0.1:27017/admin
MongoDB shell version: 2.0.9
connecting to: 127.0.0.1:27017/admin
> show collections
> ls
function () {
    return nativeHelper.apply(ls_, arguments);
}
> show dbs
admin   (empty)
db-text 0.078125GB
foobar  0.078125GB
foodar  0.078125GB
local   (empty)
> use foobar
switched to db foobar
> show collections
persons
system.indexes
> db.persons.drop()
true
> collection
Thu Mar 13 14:15:34 ReferenceError: collection is not defined (shell):1
> show collections
system.indexes


#下面的脚本可以用.json文件进行保存和编辑,之后拷贝这里进行直接运行
> var persons = [{
... name:"jim",
... age:25,
... email:"75431457@qq.com",
... c:89,m:96,e:87,
... country:"USA",
... books:["JS","C++","EXTJS","MONGODB"]
...
... },
... {
... name:"tom",
... age:25,
... email:"214557457@qq.com",
... c:75,m:66,e:97,
... country:"USA",
... books:["PHP","JAVA","EXTJS","C++"]
... },
... {
... name:"lili",
... age:26,
... email:"344521457@qq.com",
... c:75,m:63,e:97,
... country:"USA",
... books:["JS","JAVA","C#","MONGODB"]
... },
... {
... name:"zhangsan",
... age:27,
... email:"2145567457@qq.com",
... c:89,m:86,e:67,
... country:"China",
... books:["JS","JAVA","EXTJS","MONGODB"]
... },
... {
... name:"lizhenxian",
... age:27,
... email:"lizhenxian@uspcat.com",
... c:35,m:56,e:47,
... country:"Korea",
... books:["JS","JAVA","EXTJS","MONGODB"]
... },
... {
... name:"lixianli",
... age:21,
... email:"lixiaoli@uspcat.com",
... c:36,m:86,e:32,
... country:"Korea",
... books:["JS","JAVA","PHP","MONGODB"]
... },
... {
... name:"zhangsuying",
... age:22,
... email:"zhangsuying@uspcat.com",
... c:45,m:63,e:77,
... country:"Korea",
... books:["JS","JAVA","C#","MONGODB"]
... }]
>
> for(var i = 0; i<persons.length; i++){
... db.persons.insert(persons[i])
... }
>


#查看用户foobar下的数据表名
> show collections
persons
system.indexes


#查看所有的的插入到数据表persons的数据,如下脚本所示
> db.persons.find()
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "name" : "jim", "age" : 25, "ema
il" : "75431457@qq.com", "c" : 89, "m" : 96, "e" : 87, "country" : "USA", "books
" : [ "JS", "C++", "EXTJS", "MONGODB" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c22d"), "name" : "tom", "age" : 25, "ema
il" : "214557457@qq.com", "c" : 75, "m" : 66, "e" : 97, "country" : "USA", "book
s" : [ "PHP", "JAVA", "EXTJS", "C++" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c22e"), "name" : "lili", "age" : 26, "em
ail" : "344521457@qq.com", "c" : 75, "m" : 63, "e" : 97, "country" : "USA", "boo
ks" : [ "JS", "JAVA", "C#", "MONGODB" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c22f"), "name" : "zhangsan", "age" : 27,
 "email" : "2145567457@qq.com", "c" : 89, "m" : 86, "e" : 67, "country" : "China
", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c230"), "name" : "lizhenxian", "age" : 2
7, "email" : "lizhenxian@uspcat.com", "c" : 35, "m" : 56, "e" : 47, "country" :
"Korea", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c231"), "name" : "lixianli", "age" : 21,
 "email" : "lixiaoli@uspcat.com", "c" : 36, "m" : 86, "e" : 32, "country" : "Kor
ea", "books" : [ "JS", "JAVA", "PHP", "MONGODB" ] }
{ "_id" : ObjectId("53214db2877cf7fa6285c232"), "name" : "zhangsuying", "age" :
22, "email" : "zhangsuying@uspcat.com", "c" : 45, "m" : 63, "e" : 77, "country"
: "Korea", "books" : [ "JS", "JAVA", "C#", "MONGODB" ] }
>


#指定返回的键
#_id:0  表示  _id键值不显示
> db.persons.find({},{_id:0,name:1,country:1})
{ "name" : "jim", "country" : "USA" }
{ "name" : "tom", "country" : "USA" }
{ "name" : "lili", "country" : "USA" }
{ "name" : "zhangsan", "country" : "China" }
{ "name" : "lizhenxian", "country" : "Korea" }
{ "name" : "lixianli", "country" : "Korea" }
{ "name" : "zhangsuying", "country" : "Korea" }


#指定返回的键
#_id:1或者不写  表示  _id键值显示,如下所示
> db.persons.find({},{name:1,country:1})
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "name" : "jim", "country" : "USA
" }
{ "_id" : ObjectId("53214db2877cf7fa6285c22d"), "name" : "tom", "country" : "USA
" }
{ "_id" : ObjectId("53214db2877cf7fa6285c22e"), "name" : "lili", "country" : "US
A" }
{ "_id" : ObjectId("53214db2877cf7fa6285c22f"), "name" : "zhangsan", "country" :
 "China" }
{ "_id" : ObjectId("53214db2877cf7fa6285c230"), "name" : "lizhenxian", "country"
 : "Korea" }
{ "_id" : ObjectId("53214db2877cf7fa6285c231"), "name" : "lixianli", "country" :
 "Korea" }
{ "_id" : ObjectId("53214db2877cf7fa6285c232"), "name" : "zhangsuying", "country
" : "Korea" }


#指定返回的键(另外一个版本)
> db.persons.find({},{_id:0,name:1,country:1,age:1})
{ "name" : "jim", "age" : 25, "country" : "USA" }
{ "name" : "tom", "age" : 25, "country" : "USA" }
{ "name" : "lili", "age" : 26, "country" : "USA" }
{ "name" : "zhangsan", "age" : 27, "country" : "China" }
{ "name" : "lizhenxian", "age" : 27, "country" : "Korea" }
{ "name" : "lixianli", "age" : 21, "country" : "Korea" }
{ "name" : "zhangsuying", "age" : 22, "country" : "Korea" }
>

#查询条件
#查询出年龄在25到27岁之间的学生
> db.persons.find({age:{$gte:25,$lte:27}},{_id:0,name:1,age:1})
{ "name" : "jim", "age" : 25 }
{ "name" : "tom", "age" : 25 }
{ "name" : "lili", "age" : 26 }
{ "name" : "zhangsan", "age" : 27 }
{ "name" : "lizhenxian", "age" : 27 }


#查询出所有不是韩国的学生的数学成绩
> db.persons.find({country:{$ne:"Korea"}},{_id:0,m:1,country:1})
{ "m" : 96, "country" : "USA" }
{ "m" : 66, "country" : "USA" }
{ "m" : 63, "country" : "USA" }
{ "m" : 86, "country" : "China" }
>

#包含或不包含
#查询国籍是中国或者美国的学生信息
> db.persons.find({country:{$in:["USA","China"]}},{_id:0,m:1,country:1})
{ "m" : 96, "country" : "USA" }
{ "m" : 66, "country" : "USA" }
{ "m" : 63, "country" : "USA" }
{ "m" : 86, "country" : "China" }


#查询国籍不是中国或者美国的学生信息
> db.persons.find({country:{$nin:["USA","China"]}},{_id:0,m:1,country:1})
{ "m" : 56, "country" : "Korea" }
{ "m" : 86, "country" : "Korea" }
{ "m" : 63, "country" : "Korea" }
>

#OR查询
查询语文成绩大于85或者英语成绩大于90学生的信息
db.persons.find({$or:[{c:{$gt:85}},{e:{$gt:90}}]},{_id:0,c:1,e:1,name:1})
> db.persons.find({$or:[{c:{$gt:85}},{e:{$gt:90}}]},{_id:0,c:1,e:1,name:1})
{ "name" : "jim", "c" : 89, "e" : 87 }
{ "name" : "tom", "c" : 75, "e" : 97 }
{ "name" : "lili", "c" : 75, "e" : 97 }
{ "name" : "zhangsan", "c" : 89, "e" : 67 }
>

#null的使用
> db.persons.update({country:"China"},{$set:{sex:"m"}},false,true)
> db.persons.find({},{_id:0,country:1,sex:1})
{ "country" : "USA" }
{ "country" : "USA" }
{ "country" : "USA" }
{ "country" : "Korea" }
{ "country" : "Korea" }
{ "country" : "Korea" }
{ "country" : "China", "sex" : "m" }

#查询sex为null的学生(属性值为name,sex)
> db.persons.find({sex:{$in:[null]}},{_id:0,name:1,sex:1})
{ "name" : "jim" }
{ "name" : "tom" }
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }
{ "name" : "zhangsuying" }
>

#查询sex为null的学生(属性值为name、sex、country)
> db.persons.find({sex:{$in:[null]}},{_id:0,name:1,sex:1,country:1})
{ "name" : "jim", "country" : "USA" }
{ "name" : "tom", "country" : "USA" }
{ "name" : "lili", "country" : "USA" }
{ "name" : "lizhenxian", "country" : "Korea" }
{ "name" : "lixianli", "country" : "Korea" }
{ "name" : "zhangsuying", "country" : "Korea" }
>


#查询出学生的名字中存在“Li”的学生的信息
> db.persons.find({name:/li/i},{_id:0,name:1})
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }
>

#查询出学生的姓名中不存在“Li”的学生的信息
> db.persons.find({name:{$not:/li/i}},{_id:0,name:1})
{ "name" : "jim" }
{ "name" : "tom" }
{ "name" : "zhangsuying" }
{ "name" : "zhangsan" }


#查询喜欢看MONGODB和JS的学生
> db.persons.find({books:{$all:["JS","MONGODB"]}},{_id:0,name:1})
{ "name" : "jim" }
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }
{ "name" : "zhangsuying" }
{ "name" : "zhangsan" }

#便于上面方法的查看分析比较
> db.persons.find({books:{$all:["JS","MONGODB"]}},{_id:0,name:1,books:1})
{ "name" : "jim", "books" : [ "JS", "C++", "EXTJS", "MONGODB" ] }
{ "name" : "lili", "books" : [ "JS", "JAVA", "C#", "MONGODB" ] }
{ "name" : "lizhenxian", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "name" : "lixianli", "books" : [ "JS", "JAVA", "PHP", "MONGODB" ] }
{ "name" : "zhangsuying", "books" : [ "JS", "JAVA", "C#", "MONGODB" ] }
{ "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "name" : "zhangsan" }


#查询第二本书是JAVA的学生信息(关键点在books.1)
> db.persons.find({"books.1":"JAVA"},{_id:0,name:1,books:1})
{ "name" : "tom", "books" : [ "PHP", "JAVA", "EXTJS", "C++" ] }
{ "name" : "lili", "books" : [ "JS", "JAVA", "C#", "MONGODB" ] }
{ "name" : "lizhenxian", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "name" : "lixianli", "books" : [ "JS", "JAVA", "PHP", "MONGODB" ] }
{ "name" : "zhangsuying", "books" : [ "JS", "JAVA", "C#", "MONGODB" ] }
{ "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "name" : "zhangsan" }


#查询指定长度数组$Size它不能与比较查询符一起使用(这是弊端)
#查询出喜欢的书籍数量是4本的学生
> db.persons.find({books:{$size:4}},{_id:0,name:1,sex:1})
{ "name" : "jim" }
{ "name" : "tom" }
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }
{ "name" : "zhangsuying" }
{ "name" : "zhangsan", "sex" : "m" }


#为了改变上面的弊端,我们有如下方法改进
#第一步:增加字段size
> db.persons.update({},{$set:{size:4}},false,true)


#第二步:改变书籍的更新方式,每次增加书籍的时候size增加1
> db.persons.update({name:"jim"},{$push:{books:"ORACLE"},$inc:{size:1}})


#第三步:利用$gt查询(比如db.persons.find({size:{$gt:3}}))
> db.persons.find({},{_id:0,books:1,name:1,size:1})
{ "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "name" : "zhangsan", "size" :
4 }
{ "books" : [ "JS", "C++", "EXTJS", "MONGODB", "ORACLE" ], "name" : "jim", "size
" : 5 }
{ "books" : [ "PHP", "JAVA", "EXTJS", "C++" ], "name" : "tom", "size" : 4 }
{ "books" : [ "JS", "JAVA", "C#", "MONGODB" ], "name" : "lili", "size" : 4 }
{ "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "name" : "lizhenxian", "size"
: 4 }
{ "books" : [ "JS", "JAVA", "PHP", "MONGODB" ], "name" : "lixianli", "size" : 4
}
{ "books" : [ "JS", "JAVA", "C#", "MONGODB" ], "name" : "zhangsuying", "size" :
4 }
> db.persons.find({size:5},{_id:0,books:1,name:1,size:1})
{ "books" : [ "JS", "C++", "EXTJS", "MONGODB", "ORACLE" ], "name" : "jim", "size
" : 5 }


#利用shell查询出Jim喜欢看的书的数量(本代码通过查询是游标的形式展现,顾要用递归才能进行查看相应的值)
> var persons = db.persons.find({name:"jim"})
> while(persons.hasNext()){
... obj = persons.next();
... print(obj.books.length)
... }
5
>


#如下代码就是忽略了上面的注意点,而出现的错误(记得注意哦)
> var  jim = db.persons.find({name:"jim"})
> var books = jim.books
> books
> books.length
Thu Mar 13 21:33:03 TypeError: books has no properties (shell):1
> jim.books
> jim
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "age" : 25, "books" : [ "JS", "C
++", "EXTJS", "MONGODB", "ORACLE" ], "c" : 89, "country" : "USA", "e" : 87, "ema
il" : "75431457@qq.com", "m" : 96, "name" : "jim", "size" : 5 }




#$slice操作符返回文档中指定数组的内部值
#查询出Jim书架中第2~4本书
> db.persons.find({name:"jim"},{books:{"$slice":[1,3]}})
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "age" : 25, "books" : [ "C++", "
EXTJS", "MONGODB" ], "c" : 89, "country" : "USA", "e" : 87, "email" : "75431457@
qq.com", "m" : 96, "name" : "jim", "size" : 5 }


> db.persons.find({name:"jim"},{books:{"$slice":[1,3]}},{_id:0})
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "age" : 25, "books" : [ "C++", "
EXTJS", "MONGODB" ], "c" : 89, "country" : "USA", "e" : 87, "email" : "75431457@
qq.com", "m" : 96, "name" : "jim", "size" : 5 }


> db.persons.find({name:"jim"},{books:{"$slice":[1,3]},_id:0,books:1})
{ "books" : [ "JS", "C++", "EXTJS", "MONGODB", "ORACLE" ] }


> db.persons.find({name:"jim"},{books:{"$slice":[1,3]},_id:0})
{ "age" : 25, "books" : [ "C++", "EXTJS", "MONGODB" ], "c" : 89, "country" : "US
A", "e" : 87, "email" : "75431457@qq.com", "m" : 96, "name" : "jim", "size" : 5
}


#查询出最后一本书
> db.persons.find({name:"jim"},{books:{"$slice":-1},_id:0})
{ "age" : 25, "books" : [ "ORACLE" ], "c" : 89, "country" : "USA", "e" : 87, "em
ail" : "75431457@qq.com", "m" : 96, "name" : "jim", "size" : 5 }
>


#文档查询
#为Jim添加学习简历文档jim.json,具体代码如下所示
> var jim = [{
... school:"K",
... score:"A"
...
... },{
... school:"L",
... score:"B"
... },{
... school:"J",
... score:"A+"
... }]


#更新数据库
> db.persons.update({name:"jim"},{$set:{school:jim}})


#查询出在K上过学的学生
#这个我们用绝对匹配可以完成,但是有些问题(找找问题?顺序?总要带着score?)
> db.persons.find({school:{school:"K",score:"A"}},{_id:0,school:1})
{ "school" : [  {       "school" : "K",         "score" : "A" },        {
"school" : "L",         "score" : "B" },        {       "school" : "J",
"score" : "A+" } ] }


#为了更好的诠释上面的问题,下面针对上面而出现的代码
> db.persons.find({school:{school:"K"}},{_id:0,school:1})
> db.persons.find({school:{score:"A",school:"K"}},{_id:0,school:1})


#为了解决顺序的问题我可以用对象“.”的方式定位
> db.persons.find({"school.score":"A","school.school":"K"},{_id:0,school:1})
{ "school" : [  {       "school" : "K",         "score" : "A" },        {
"school" : "L",         "score" : "B" },        {       "school" : "J",
"score" : "A+" } ] }


#单条条件组查询$elemMatch(注意:数据表中有测显示,没有则不显示数据)
> db.persons.find({school:{$elemMatch:{school:"J",score:"A"}}},{_id:0,school:1})
> db.persons.find({school:{$elemMatch:{school:"K",score:"A"}}},{_id:0,school:1})
{ "school" : [  {       "school" : "K",         "score" : "A" },        {
"school" : "L",         "score" : "B" },        {       "school" : "J",
"score" : "A+" } ] }
>

#复杂的查询器 $where
>
> db.persons.find({"$where":function(){
... var books = this.books;
... var school = this.school;
... if(this.age > 22){
... var php = null;
... for( var i = 0; i<books.length; i++){
... if(books[i] == "C++"){
... php = books[i];
... if(school){
... for(var j = 0; j < school.length; j++){
... if(school[j].school == "K"){
... return true;
... }
... }
... break;
... }
...
... }
... }
... }
... }})
{ "_id" : ObjectId("53214db2877cf7fa6285c22c"), "age" : 25, "books" : [ "JS",
++", "EXTJS", "MONGODB", "ORACLE" ], "c" : 89, "country" : "USA", "e" : 87, "e
il" : "75431457@qq.com", "m" : 96, "name" : "jim", "school" : [         {
"school" : "K",         "score" : "A" },        {       "school" : "L",
"score" : "B" },        {       "school" : "J",         "score" : "A+" } ], "s
e" : 5 }
>


#limit返回指定的数据条数
#查询全部数据信息(只摘录name字段)
> db.persons.find({},{_id:0,name:1})
{ "name" : "zhangsan" }
{ "name" : "tom" }
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }
{ "name" : "zhangsuying" }
{ "name" : "jim" }


#查询出persons文档中前5条数据
> db.persons.find({},{_id:0,name:1}).limit(5)
{ "name" : "zhangsan" }
{ "name" : "tom" }
{ "name" : "lili" }
{ "name" : "lizhenxian" }
{ "name" : "lixianli" }


#skip返回指定的数据的跨度
#查询出persons文档中5~10条的数据(本数据库中只有7条数据)
> db.persons.find({},{_id:0,name:1}).limit(5).skip(5)
{ "name" : "zhangsuying" }
{ "name" : "jim" }


#sort返回按照年龄排序的数据[1,-1]
> db.persons.find({},{_id:0,name:1,age:1}).limit(5).skip(5).sort({age:1})
{ "age" : 27, "name" : "zhangsan" }
{ "age" : 27, "name" : "lizhenxian" }


#用sort按照年龄从少到大排序
> db.persons.find({},{_id:0,name:1,age:1}).sort({age:1})
{ "age" : 21, "name" : "lixianli" }
{ "age" : 22, "name" : "zhangsuying" }
{ "age" : 25, "name" : "tom" }
{ "age" : 25, "name" : "jim" }
{ "age" : 26, "name" : "lili" }
{ "age" : 27, "name" : "zhangsan" }
{ "age" : 27, "name" : "lizhenxian" }


#用sort按照年龄从大到少排序
> db.persons.find({},{_id:0,name:1,age:1}).sort({age:-1})
{ "age" : 27, "name" : "zhangsan" }
{ "age" : 27, "name" : "lizhenxian" }
{ "age" : 26, "name" : "lili" }
{ "age" : 25, "name" : "tom" }
{ "age" : 25, "name" : "jim" }
{ "age" : 22, "name" : "zhangsuying" }
{ "age" : 21, "name" : "lixianli" }

#创建简单的索引
#数据准备index.js
#检查数据库中有那些表
> show collections
persons
system.indexes


#通过上面的index.js脚本创建一个books数据表
> for(var i = 0; i<200000; i++){
... db.books.insert({number:i,name:i+"book"})
... }

#第一步:先检验一下查询性能(一般用这样的方式进行检测性能,耗时性能)
> var start = new Date()
> db.books.find({number:65871})
{ "_id" : ObjectId("5322b866877cf7fa6286c382"), "number" : 65871, "name" : "6587
1book" }
> var end = new Date()
> end - start
14400


#第二步:为number创建索引
> db.books.ensureIndex({number:1})


#第三步:在执行第一步的代码可以看出有数量级的性能提升
> var start = new Date()
> db.books.find({number:65871})
{ "_id" : ObjectId("5322b866877cf7fa6286c382"), "number" : 65871, "name" : "6587
1book" }
> var end = new Date()
> end - start
159
>

#Expain
#如何详细查看本次查询使用哪个索引和查询数据的状态信息
> db.persons.find({name:"88888book"}).explain()
{
        "cursor" : "BasicCursor",
        "nscanned" : 7,
        "nscannedObjects" : 7,
        "n" : 0,
        "millis" : 881,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : false,
        "indexOnly" : false,
        "indexBounds" : {
        }
}
>


详细参数注解:
"cursor" : "BasicCursor",  使用索引
        "nscanned" : 7,   查到几个文档
        "millis" : 881,   查询时间


#展现数据表中的表的属性
> show collections
books
persons
system.indexes


#用如下命令,在shell查看数据库已经创建的索引
> db.system.indexes.find()
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "foobar.persons", "name" : "_id_" }
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "foobar.books", "name" : "_id_" }
{ "v" : 1, "key" : { "number" : 1 }, "ns" : "foobar.books", "name" : "number_1"
}


#用如下命令
> db.system.namespaces.find()
{ "name" : "foobar.system.indexes" }
{ "name" : "foobar.persons" }
{ "name" : "foobar.persons.$_id_" }
{ "name" : "foobar.books" }
{ "name" : "foobar.books.$_id_" }
{ "name" : "foobar.books.$number_1" }
>

#空间索引创建
#下面是一些预备工作(将mongodb连接服务器,看看相关信息)
> show dbs
db-text 0.078125GB
foobar  0.078125GB
foodar  0.078125GB
local   (empty)

> use foobar
switched to db foobar


> show collections
books
persons
system.indexes

#mongodb提供强大的空间索引可以查询出一定范围的地理坐标
#先准备数据map.json,如下代码所示
> var map = [{
... "gis" : {
... "x" :185,
... "y" :150
... }
... },{
... "gis" : {
... "x" :70,
... "y" :180
... }
... },{
... "gis" : {
... "x" :75,
... "y" :180
... }
... },{
... "gis" : {
... "x" :185,
... "y" :185
... }
... },{
... "gis" : {
... "x" :65,
... "y" :185
... }
... },{
... "gis" : {
... "x" :50,
... "y" :50
... }
... },{
... "gis" : {
... "x" :30,
... "y" :160
... }
... },{
... "gis" : {
... "x" :45,
... "y" :155
... }
... },{
... "gis" : {
... "x" :90,
... "y" :20
... }
... },{
... "gis" : {
... "x" :100,
... "y" :170
... }
... },{
... "gis" : {
... "x" :20,
... "y" :25
... }
... },{
... "gis" : {
... "x" :90,
... "y" :75
... }
... },{
... "gis" : {
... "x" :125,
... "y" :45
... }
... },{
... "gis" : {
... "x" :70,
... "y" :125
... }
... },{
... "gis" : {
... "x" :65,
... "y" :45
... }
... },{
... "gis" : {
... "x" :35,
... "y" :150
... }
... },{
... "gis" : {
... "x" :150,
... "y" :80
... }
... }]
> for(var i = 0; i<map.length; i++){
... db.map.insert(map[i])
... }


#添加2D索引
#默认会创建一个[-180,180]之间的2D索引(如果不添加索引的话)
> db.map.ensureIndex({"gis":"2d"},{min:-1,max:201})


#查询点(70,180)最近的3个点
> db.map.find({"gis":{$near:[70,180]}},{gis:1,_id:0}).limit(3)
{ "gis" : { "x" : 70, "y" : 180 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 65, "y" : 185 } }


#查询以点(50,50)和点(190,190)为对角线的正方形的所有的点
#只显示三个点
> db.map.find({"gis":{"$within":{$box:[[50,50],[190,190]]}}},{gis:1,_id:0}).limi
{ "gis" : { "x" : 150, "y" : 80 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 70, "y" : 180 } }


#显示这个区域的所有的点
> db.map.find({"gis":{"$within":{$box:[[50,50],[190,190]]}}},{gis:1,_id:0})
{ "gis" : { "x" : 150, "y" : 80 } }
{ "gis" : { "x" : 75, "y" : 180 } }
{ "gis" : { "x" : 70, "y" : 180 } }
{ "gis" : { "x" : 65, "y" : 185 } }
{ "gis" : { "x" : 70, "y" : 125 } }
{ "gis" : { "x" : 90, "y" : 75 } }
{ "gis" : { "x" : 50, "y" : 50 } }
{ "gis" : { "x" : 185, "y" : 185 } }
{ "gis" : { "x" : 185, "y" : 150 } }
{ "gis" : { "x" : 100, "y" : 170 } }


#查询出以圆心为(56,80)半径为50规划下的圆心面积中的点
> db.map.find({"gis":{"$within":{$center:[[56,80],50]}}},{gis:1,_id:0})
{ "gis" : { "x" : 50, "y" : 50 } }
{ "gis" : { "x" : 70, "y" : 125 } }
{ "gis" : { "x" : 65, "y" : 45 } }
{ "gis" : { "x" : 90, "y" : 75 } }


########进入新的一节###########
> show collections
books
map
persons
system.indexes


#Count 查询persons中所有学生的人数
> db.persons.count()
7
> db.persons.find().count()
7


#Count用法 
#查询persons中美国学生的人数
> db.persons.find({country:"USA"}).count()
3


#Distinct用法
#查询出persons中一共有多少个国家,并分别是什么
> db.runCommand({distinct:"persons",key:"country"}).values
[ "China", "USA", "Korea" ]
> db.runCommand({distinct:"persons",key:"country"})
{
        "values" : [
                "China",
                "USA",
                "Korea"
        ],
        "stats" : {
                "n" : 7,
                "nscanned" : 7,
                "nscannedObjects" : 7,
                "timems" : 0,
                "cursor" : "BasicCursor"
        },
        "ok" : 1
}
>


#Group的用法(插入如下代码,回车会出现如下结果,相关代码的脚本在group.js文件中)
#group函数相关代码的注解
db.runCommand({group:{
ns:"persons", //集合的名字
key:{"country":true}, //分组的键对象
initial:{m:0}, //初始化累加器
$reduce:function(doc,prev){ //组分解器
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
condition:{m:{$gt:90}} //条件
}})




#查出persons中每个国家学生数学成绩最好的学生信息(数学成绩必须90分以上)
> db.runCommand({group:{
... ns:"persons",
... key:{"country":true},
... initial:{m:0},
... $reduce:function(doc,prev){
... if(doc.m > prev.m){
... prev.m = doc.m;
... prev.name = doc.name;
... prev.country = doc.country;
... }
... },
... condition:{m:{$gt:90}}
... }})


{
        "retval" : [
                {
                        "country" : "China",
                        "m" : 96,
                        "name" : "zhangsan"
                },
                {
                        "country" : "USA",
                        "m" : 96,
                        "name" : "jim"
                },
                {
                        "country" : "Korea",
                        "m" : 93,
                        "name" : "zhangsuying"
                }
        ],
        "count" : 4,
        "keys" : 3,
        "ok" : 1
}
>


#在上面的基础上,把每个人的信息链接起来写一个描述赋值到m上
finalize:function(prev){ //组完成器
prev.m = prev.nam+" Math scores " + prev.m
},


#查出persons中每个国家学生数学成绩最好的学生信息
#并把每个人的信息链接起来写到一个描述值到m(比较与上面语句的区别)
> db.runCommand({group:{
... ns:"persons",
... key:{"country":true},
... initial:{m:0},
... $reduce:function(doc,prev){
... if(doc.m > prev.m){
... prev.m = doc.m;
... prev.name = doc.name;
... prev.country = doc.country;
... }
... },
... finalize:function(prev){
... prev.m = prev.name +" Math scores " + prev.m
... },
... condition:{m:{$gt:90}}
... }})
{
        "retval" : [
                {
                        "country" : "China",
                        "m" : "zhangsan Math scores 96",
                        "name" : "zhangsan"
                },
                {
                        "country" : "USA",
                        "m" : "jim Math scores 96",
                        "name" : "jim"
                },
                {
                        "country" : "Korea",
                        "m" : "zhangsuying Math scores 93",
                        "name" : "zhangsuying"
                }
        ],
        "count" : 4,
        "keys" : 3,
        "ok" : 1
}
>


#Sat Mar 15 14:21:02 malformed UTF-8 character sequence at offset 316
#如上错误解决(在插入group代码时,出现的一个错误,不晓得哪里出错了)


#插入如下一段代码
> db.persons.insert({
... name:"USPCAT",
... age:27,
... email:"2145567457@qq.com",
... c:89,m:100,e:67,
... counTry:"China",
... books:["JS","JAVA","EXTJS","MONGODB"]
... })
>


#下面代码主要解决(country 和 counTry属性,
#而进行上面几个列子的要求进行处理)
> db.runCommand({group:{
... ns:"persons",
... $keyf:function(doc){
... if(doc.counTry){
... return {country:doc.counTry}
... }else{
... return {country:doc.country}
... }
... },
... initial:{m:0},
... $reduce:function(doc,prev){
... if(doc.m > prev.m){
... prev.m = doc.m;
... prev.name = doc.name;
... if(doc.country){
... prev.country = doc.country;
... }else{
... prev.country = doc.counTry;
... }
... }
... },
... finalize:function(prev){
... prev.m = prev.name +" Math scores " + prev.m
... },
... condition:{m:{$gt:90}}
... }})
{
        "retval" : [
                {
                        "country" : "China",
                        "m" : "USPCAT Math scores 100",
                        "name" : "USPCAT"
                },
                {
                        "country" : "USA",
                        "m" : "jim Math scores 96",
                        "name" : "jim"
                },
                {
                        "country" : "Korea",
                        "m" : "zhangsuying Math scores 93",
                        "name" : "zhangsuying"
                },
                {
                        "country" : null,
                        "m" : "USPCAT Math scores 100",
                        "name" : "USPCAT"
                }
        ],
        "count" : 7,
        "keys" : 4,
        "ok" : 1
}
>


#命令执行器runCommand
#用命令执行完成一次删除表的操作
db.runCommand({drop:"map"})


#效果如下所示
>
> db.runCommand({drop:"map"})
{
        "nIndexesWas" : 2,
        "msg" : "indexes dropped for collection",
        "ns" : "foobar.map",
        "ok" : 1
}


#查看是否将map这张表进行删除了(从如下结果可以查看没有任何信息,说明Map表被删除了)
> db.map.find()
>


#查看mongoDB为我们提供的命令
#在shell中执行db.listCommands()


#下面就是在shell窗口中执行如上命令,但是由于shell窗口的缓存限制,还没有全部显示出来
> db.listCommands()
distinct: read-lock
  { distinct : 'collection name' , key : 'a.b' , query : {} }


driverOIDTest: no-lock
  no help defined


drop: write-lock
  drop a collection
  {drop : <collectionName>}


dropDatabase: write-lock
  drop (delete) this database


dropIndexes: write-lock
  drop indexes for a collection


emptycapped: write-lock
  no help defined


eval: no-lock
  Evaluate javascript at the server.
  http://www.mongodb.org/display/DOCS/Server-side+Code+Execution


features: no-lock
  return build level feature settings


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


findAndModify: write-lock
  { findAndModify: "collection", query: {processed:false}, update: {$set: {proce
ssed: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

forceerror: no-lock
  for testing purposes only.  forces a user assertion exception


fsync: write-lock adminOnly  slaveOk
  http://www.mongodb.org/display/DOCS/fsync+Command


geoNear: read-lock
  http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geo
NearCommand


geoSearch: read-lock
  no help defined


geoWalk: read-lock
  no help defined


getCmdLineOpts: no-lock adminOnly  slaveOk
  get argv


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


getLog: no-lock adminOnly  slaveOk
  { getLog : '*' }  OR { getLog : 'global' }


getParameter: no-lock adminOnly  slaveOk
  get administrative option(s)
  example:
  { getParameter:1, notablescan:1 }
  supported so far:
    quiet
    notablescan
    logLevel
    syncdelay
  { getParameter:'*' } to get everything




getPrevError: no-lock
  check for errors since last reseterror commandcal


getShardMap: no-lock adminOnly  slaveOk
  internal


getShardVersion: no-lock adminOnly  slaveOk
   example: { getShardVersion : 'alleyinsider.foo'  }


getnonce: no-lock
  internal


getoptime: no-lock
  internal


godinsert: write-lock
  internal. for testing only.


group: read-lock
  http://www.mongodb.org/display/DOCS/Aggregation


handshake: no-lock
  internal


isMaster: no-lock
  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 }


journalLatencyTest: no-lock adminOnly  slaveOk
  test how long to write and fsync to a test file in the journal/ directory


listCommands: no-lock
  get a list of all db commands


listDatabases: no-lock adminOnly  slaveOk
  list databases on this server


logRotate: no-lock adminOnly  slaveOk
  no help defined


logout: no-lock
  de-authenticate


mapReduce: no-lock
  Run a map/reduce operation on the server.
  Note this is used for aggregation, not querying, in MongoDB.
  http://www.mongodb.org/display/DOCS/MapReduce


mapreduce.shardedfinish: no-lock
  no help defined


medianKey: read-lock
  Internal command.
  example: { medianKey:"blog.posts", keyPattern:{x:1}, min:{x:10}, max:{x:55} }
  NOTE: This command may take a while to run


moveChunk: no-lock adminOnly  slaveOk
  should not be calling this directly00000000006336B0


ping: no-lock
  a way to check that the server is alive. responds immediately even if server i
s in a db lock.


profile: write-lock
  enable or disable performance profiling
  { profile : <n> }
  0=off 1=log slow ops 2=log all
  -1 to get current values
  http://www.mongodb.org/display/DOCS/Database+Profiler


reIndex: write-lock
  re-index a collection


renameCollection: write-lock adminOnly  slaveOk
   example: { renameCollection: foo.a, to: bar.b }


repairDatabase: write-lock
  repair database.  also compacts. note: slow.


replSetElect: no-lock adminOnly  slaveOk
  internal


replSetFreeze: no-lock adminOnly  slaveOk
  { 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 e
xpires.
  You can call again with {replSetFreeze:0} to unfreeze sooner.
  A process restart unfreezes the member also.


  http://www.mongodb.org/display/DOCS/Replica+Set+Commands


replSetFresh: no-lock adminOnly  slaveOk
  internal


replSetGetRBID: no-lock adminOnly  slaveOk
  internal


replSetGetStatus: no-lock adminOnly  slaveOk
  Report status of a replica set from the POV of this server
  { replSetGetStatus : 1 }
  http://www.mongodb.org/display/DOCS/Replica+Set+Commands


replSetHeartbeat: no-lock adminOnly  slaveOk
  internal


replSetInitiate: no-lock adminOnly  slaveOk
  Initiate/christen a replica set.
  http://www.mongodb.org/display/DOCS/Replica+Set+Commands


replSetReconfig: no-lock adminOnly  slaveOk
  Adjust configuration of a replica set
  { replSetReconfig : config_object }
  http://www.mongodb.org/display/DOCS/Replica+Set+Commands


replSetStepDown: no-lock adminOnly  slaveOk
  { replSetStepDown : <seconds> }
  Step down as primary.  Will not try to reelect self for the specified time per
iod (1 minute if no numeric secs value specified).
  (If another member with same priority takes over in the meantime, it will stay
 primary.)
  http://www.mongodb.org/display/DOCS/Replica+Set+Commands


replSetTest: no-lock adminOnly  slaveOk
  Just for regression tests.




resetError: no-lock
  reset error state (used with getpreverror)


resync: write-lock adminOnly  slaveOk
  resync (from scratch) an out of date replica slave.
  http://www.mongodb.org/display/DOCS/Master+Slave


serverStatus: no-lock
  returns lots of administrative server statistics


setParameter: no-lock adminOnly  slaveOk
  set administrative option(s)
  { setParameter:1, <param>:<value> }
  supported so far:
    journalCommitInterval
    logLevel
    notablescan
    quiet
    syncdelay




setShardVersion: no-lock adminOnly  slaveOk
   example: { setShardVersion : 'alleyinsider.foo' , version : 1 , configdb : ''
 }


shardingState: write-lock adminOnly  slaveOk
  no help defined


shutdown: no-lock adminOnly  slaveOk
  shutdown the database.  must be ran against admin db and either (1) ran from l
ocalhost or (2) authenticated. If this is a primary in a replica set and there i
s 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 member
s to catch up.


sleep: no-lock adminOnly  slaveOk
  internal testing command.  Makes db block (in a read lock) for 100 seconds
  w:true write lock. secs:<seconds>


splitChunk: no-lock adminOnly  slaveOk
  internal command usage only
  example:
   { splitChunk:"db.foo" , keyPattern: {a:1} , min : {a:100} , max: {a:200} { sp
litKeys : [ {a:150} , ... ]}


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


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


top: read-lock adminOnly  slaveOk
  usage by collection, in micros


unsetSharding: no-lock adminOnly  slaveOk
   example: { unsetSharding : 1 }


validate: read-lock
  Validate contents of a namespace by scanning its data structures for correctne
ss.  Slow.
  Add full:true option to do a more thorough check


whatsmyuri: no-lock
  {whatsmyuri:1}


writeBacksQueued: no-lock adminOnly  slaveOk
  Returns whether there are operations in the writeback queue at the time the co
mmand was called. This is an internal command


writebacklisten: no-lock adminOnly  slaveOk
  internal





#访问网址来查看mongoDB为我们提供的命令http://localhost:28017/_commands
#注意用网址来查看mongoDB API的相关命令的时候会查看不了网页
#问题解决方案,主要是在配置mongodb服务器的时候,要加一个参数  --rest
mongod  --dbpath   H:\MongoDB\MongoDBDATA209 --rest




#常用命令
#查询服务器版本和主机操作系统
> db.runCommand({buildInfo:1})
{
        "version" : "2.0.9",
        "gitVersion" : "7e34cb36a6ae64d527c0b0da81fa967606c55433",
        "sysInfo" : "windows sys.getwindowsversion(major=6, minor=1, build=7601,
 platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_42",
        "versionArray" : [
                2,
                0,
                9,
                0
        ],
        "bits" : 64,
        "debug" : false,
        "maxBsonObjectSize" : 16777216,
        "ok" : 1
}
>


#查询执行集合的详细信息、大小、空间、索引等…………
> db.runCommand({collStats:"persons"})
{
        "ns" : "foobar.persons",
        "count" : 10,
        "size" : 3444,
        "avgObjSize" : 344.4,
        "storageSize" : 12288,
        "numExtents" : 1,
        "nindexes" : 1,
        "lastExtentSize" : 12288,
        "paddingFactor" : 1.47,
        "flags" : 1,
        "totalIndexSize" : 8176,
        "indexSizes" : {
                "_id_" : 8176
        },
        "ok" : 1
}
>


#查看操作集合最后一次错误信息
> db.runCommand({getLastError:"persons"})
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }



#创建固定集合
#创建一个新的固定集合要求大小是100个字节,可以存储文档10个
> db.createCollection("mucoll",{size:100,capped:true,max:10})
{ "ok" : 1 }


#把一个普通集合转换成固定集合
> db.runCommand({"convertToCapped":"persons",size:100000})
{ "ok" : 1 }


#为了演示反向排序情况,我们先得在mycoll表中插入几个属性
> db.mycoll.insert({i:0})
> db.mycoll.insert({i:1})
> db.mycoll.insert({i:2})
> db.mycoll.insert({i:3})


#反向排序,默认是插入顺序排序
> db.mycoll.find()
{ "_id" : ObjectId("532650c434de64a8d6d3db34"), "i" : 0 }
{ "_id" : ObjectId("532650c734de64a8d6d3db35"), "i" : 1 }
{ "_id" : ObjectId("532650cc34de64a8d6d3db36"), "i" : 2 }
{ "_id" : ObjectId("532650d634de64a8d6d3db37"), "i" : 3 }


#查询固定集合mycoll并且反向排序
> db.mycoll.find().sort({$natural:-1})
{ "_id" : ObjectId("532650d634de64a8d6d3db37"), "i" : 3 }
{ "_id" : ObjectId("532650cc34de64a8d6d3db36"), "i" : 2 }
{ "_id" : ObjectId("532650c734de64a8d6d3db35"), "i" : 1 }
{ "_id" : ObjectId("532650c434de64a8d6d3db34"), "i" : 0 }
>


########################################################
使用GridFS,主要用于云计算中的文件存储
########################################################
#查看GridFS的所有功能
#cmd  -->  mongofiles
#注解:这个是win7下的cmd命令, 不要打错了
C:\Users\Administrator>mongofiles
connected to: 127.0.0.1
ERROR: need command


usage: mongofiles [options] command [gridfs filename]
command:
  one of (list|search|put|get)
  list - list all files.  'gridfs filename' is an optional prefix
         which listed filenames must begin with.
  search - search all files. 'gridfs filename' is a substring
           which listed filenames must contain.
  put - add a file with filename 'gridfs filename'
  get - get a file with filename 'gridfs filename'
  delete - delete all files with filename 'gridfs filename'
options:
  --help                  produce help message
  -v [ --verbose ]        be more verbose (include multiple times for more
                          verbosity e.g. -vvvvv)
  --version               print the program's version and exit
  -h [ --host ] arg       mongo host to connect to ( <set name>/s1,s2 for sets)
  --port arg              server port. Can also use --host hostname:port
  --ipv6                  enable IPv6 support (disabled by default)
  -u [ --username ] arg   username
  -p [ --password ] arg   password
  --dbpath arg            directly access mongod database files in the given
                          path, instead of connecting to a mongod  server -
                          needs to lock the data directory, so cannot be used
                          if a mongod is currently accessing the same path
  --directoryperdb        if dbpath specified, each db is in a separate
                          directory
  --journal               enable journaling
  -d [ --db ] arg         database to use
  -c [ --collection ] arg collection to use (some commands)
  -l [ --local ] arg      local filename for put|get (default is to use the
                          same name as 'gridfs filename')
  -t [ --type ] arg       MIME type for put (default is to omit)
  -r [ --replace ]        Remove other files with same name after PUT




#上传一个文件到mongodb数据库中
#记得还是在win7下的cmd命令中输入如下命令
#上传成功了,就如下所示
C:\Users\Administrator>mongofiles -d foobar -l "F:\\test.txt" put "test.txt"
connected to: 127.0.0.1
added file: { _id: ObjectId('5326538eca8357e967d4e29c'), filename: "test.txt", c
hunkSize: 262144, uploadDate: new Date(1395020686173), md5: "a70e5f28e1cec88261c
96c5222aab62e", length: 1989 }
done!


#你可以在MongoVUE中查看相应的文件(下面是MongoVUE下的Learn Shell命令)
#比较遗憾是这条命令在win7下的cmd命令中不能打开
mongofiles -d foobar -l 'C:\Users\Administrator\AppData\Local\Temp\test.txt' get 'test.txt'
[ 9:45:03 ]
db.fs.files.find();
[ 9:23:32 ]
db.fs.files.find();
An easy way to learn shell commands. As you use MongoVUE, corresponding shell commands are displayed here for a quick reference.


#集合查看
#先检查表中的内容
> show collections
books
fs.chunks
fs.files
mucoll
mycoll
persons
system.indexes


#查看文件命令一
> db.fs.files.find()
{ "_id" : ObjectId("5326538eca8357e967d4e29c"), "filename" : "test.txt", "chunkS
ize" : 262144, "uploadDate" : ISODate("2014-03-17T01:44:46.173Z"), "md5" : "a70e
5f28e1cec88261c96c5222aab62e", "length" : 1989 }


#查看文件命令二
> db.fs.chunks.find()
{ "_id" : ObjectId("5326538e670428b8e74c0cf9"), "files_id" : ObjectId("5326538ec
a8357e967d4e29c"), "n" : 0, "data" : BinData(0,"aHR0cDovL3dlbmt1Lml0MTY4LmNvbS96
aHVhbnRpLzEwMTEzMy9SaGFkb29wXzEwMTEzMjYwMTkuc2h0bWwNCg0KDQpodHRwOi8vd3d3LnNlYXJj
aGRhdGFiYXNlLmNvbS5jbi9zaG93Y29udGVudF81NDI0Ny5odG0NCg0KaHR0cDovL2Jsb2cuY3Nkbi5u
ZXQvbGVlaG9uZzIwMDUvYXJ0aWNsZS9kZXRhaWxzLzg1MzUzMDYNCg0KDQoxMy8xMi8yMyAxODowOTo1
NCBXQVJOIHV0aWwuTmF0aXZlQ29kZUxvYWRlcjogVW5hYmxlIHRvIGxvYWQgbmF0aXZlLWhhZG9vcCBs
aWJyYXJ5IGZvciB5b3VyIHBsYXRmb3JtLi4uIHVzaW5nIGJ1aWx0aW4tamF2YSBjbGFzc2VzIHdoZXJl
IGFwcGxpY2FibGUNCjEzLzEyLzIzIDE4OjA5OjU0IEVSUk9SIHNlY3VyaXR5LlVzZXJHcm91cEluZm9y
bWF0aW9uOiBQcml2aWxlZGdlZEFjdGlvbkV4Y2VwdGlvbiBhczpsaXVjaHVibyBjYXVzZTpqYXZhLmlv
LklPRXhjZXB0aW9uOiBGYWlsZWQgdG8gc2V0IHBlcm1pc3Npb25zIG9mIHBhdGg6IFx0bXBcaGFkb29w
LWxpdWNodWJvXG1hcHJlZFxzdGFnaW5nXGxpdWNodWJvNDY1NjUyMDQ2XC5zdGFnaW5nIHRvIDA3MDAN
CkV4Y2VwdGlvbiBpbiB0aHJlYWQgIm1haW4iIGphdmEuaW8uSU9FeGNlcHRpb246IEZhaWxlZCB0byBz
ZXQgcGVybWlzc2lvbnMgb2YgcGF0aDogXHRtcFxoYWRvb3AtbGl1Y2h1Ym9cbWFwcmVkXHN0YWdpbmdc
bGl1Y2h1Ym80NjU2NTIwNDZcLnN0YWdpbmcgdG8gMDcwMA0KCWF0IG9yZy5hcGFjaGUuaGFkb29wLmZz
LkZpbGVVdGlsLmNoZWNrUmV0dXJuVmFsdWUoRmlsZVV0aWwuamF2YTo2OTEpDQoJYXQgb3JnLmFwYWNo
ZS5oYWRvb3AuZnMuRmlsZVV0aWwuc2V0UGVybWlzc2lvbihGaWxlVXRpbC5qYXZhOjY2NCkNCglhdCBv
cmcuYXBhY2hlLmhhZG9vcC5mcy5SYXdMb2NhbEZpbGVTeXN0ZW0uc2V0UGVybWlzc2lvbihSYXdMb2Nh
bEZpbGVTeXN0ZW0uamF2YTo1MTQpDQoJYXQgb3JnLmFwYWNoZS5oYWRvb3AuZnMuUmF3TG9jYWxGaWxl
U3lzdGVtLm1rZGlycyhSYXdMb2NhbEZpbGVTeXN0ZW0uamF2YTozNDkpDQoJYXQgb3JnLmFwYWNoZS5o
YWRvb3AuZnMuRmlsdGVyRmlsZVN5c3RlbS5ta2RpcnMoRmlsdGVyRmlsZVN5c3RlbS5qYXZhOjE5MykN
CglhdCBvcmcuYXBhY2hlLmhhZG9vcC5tYXByZWR1Y2UuSm9iU3VibWlzc2lvbkZpbGVzLmdldFN0YWdp
bmdEaXIoSm9iU3VibWlzc2lvbkZpbGVzLmphdmE6MTI2KQ0KCWF0IG9yZy5hcGFjaGUuaGFkb29wLm1h
cHJlZC5Kb2JDbGllbnQkMi5ydW4oSm9iQ2xpZW50LmphdmE6OTQyKQ0KCWF0IG9yZy5hcGFjaGUuaGFk
b29wLm1hcHJlZC5Kb2JDbGllbnQkMi5ydW4oSm9iQ2xpZW50LmphdmE6OTM2KQ0KCWF0IGphdmEuc2Vj
dXJpdHkuQWNjZXNzQ29udHJvbGxlci5kb1ByaXZpbGVnZWQoTmF0aXZlIE1ldGhvZCkNCglhdCBqYXZh
eC5zZWN1cml0eS5hdXRoLlN1YmplY3QuZG9BcyhVbmtub3duIFNvdXJjZSkNCglhdCBvcmcuYXBhY2hl
LmhhZG9vcC5zZWN1cml0eS5Vc2VyR3JvdXBJbmZvcm1hdGlvbi5kb0FzKFVzZXJHcm91cEluZm9ybWF0
aW9uLmphdmE6MTE5MCkNCglhdCBvcmcuYXBhY2hlLmhhZG9vcC5tYXByZWQuSm9iQ2xpZW50LnN1Ym1p
dEpvYkludGVybmFsKEpvYkNsaWVudC5qYXZhOjkzNikNCglhdCBvcmcuYXBhY2hlLmhhZG9vcC5tYXBy
ZWR1Y2UuSm9iLnN1Ym1pdChKb2IuamF2YTo1NTApDQoJYXQgb3JnLmFwYWNoZS5oYWRvb3AubWFwcmVk
dWNlLkpvYi53YWl0Rm9yQ29tcGxldGlvbihKb2IuamF2YTo1ODApDQoJYXQgY24uZGF0YWd1cnUuaGFk
b29wLkJhc2VTdGF0aW9uRGF0YVByZXByb2Nlc3MucnVuKEJhc2VTdGF0aW9uRGF0YVByZXByb2Nlc3Mu
amF2YToyMzMpDQoJYXQgb3JnLmFwYWNoZS5oYWRvb3AudXRpbC5Ub29sUnVubmVyLnJ1bihUb29sUnVu
bmVyLmphdmE6NjUpDQoJYXQgY24uZGF0YWd1cnUuaGFkb29wLkJhc2VTdGF0aW9uRGF0YVByZXByb2Nl
c3MubWFpbihCYXNlU3RhdGlvbkRhdGFQcmVwcm9jZXNzLmphdmE6MjU1KQ0K") }
>


#查看文件的内容(win7下cmd命令)
#出现如下错误,但是VUE可以查看,shell无法打开文件
C:\Users\Administrator>mongofiles -d foobar -l get "test.txt"
connected to: 127.0.0.1
ERROR: need a filename


#查看所有的文件(win7下cmd命令)
C:\Users\Administrator>mongofiles -d foobar list
connected to: 127.0.0.1
test.txt        1989


#删除已经存在的文件(win7下cmd命令)
C:\Users\Administrator>mongofiles -d foobar delete "test.txt"
connected to: 127.0.0.1
done!


#Eval相关操作
#查看用户为foodbar数据表的集合
> show collections
books
fs.chunks
fs.files
mucoll
mycoll
persons
system.indexes


#服务器上运行eval
> db.eval("function(name){return name}","book")
book


#Javascript的存储
#在服务器上保存js变量函数,用于供全局调用
#把变量加载到特殊集合system.js中
#查看特殊集合system.js的属性
> db.system.js.find()


#在特殊集合system.js中插入如下内容
> db.system.js.insert({_id:"name",value:"uspcat"})


#查看特殊集合system.js的属性
> db.system.js.find()
{ "_id" : "name", "value" : "uspcat" }


#错误调用
> db.eval("return gook")
Mon Mar 17 10:10:52 uncaught exception: {
        "errno" : -3,
        "errmsg" : "invoke failed: JS Error: ReferenceError: gook is not defined
 nofile_a:0",
        "ok" : 0
}


#正确调用
> db.eval("return name")
uspcat
>


#Javascript的存储复杂的情况(函数的调用)
#system.js相当于Oracle中的存储过程,因为value不仅可以写变量
#还可以写函数体,也可以写Javascript代码
> db.system.js.insert({_id:"showname",value:function(){return 12}})
> db.system.js.find()
{ "_id" : "name", "value" : "uspcat" }
{ "_id" : "showname", "value" : function cf__1__f_() { return 12; } }
> db.eval("showname")
function cf__2__f_cf__4__f_() {
    return 12;
}
> db.eval("showname()")
12
>




#导入导出数据
#打开cmd(用win7下的cmd命令)
#利用mongoexport命令
#把数据表foobar中的persons集合导出(在win7下cmd操作)
C:\Users\Administrator>mongoexport -d foobar -c persons  -o F:/persons.json
connected to: 127.0.0.1
exported 10 records


#之后找到win7操作系统(本实验环境)F:/persons.json文件,查看信息如下图所示,
{ "_id" : { "$oid" : "53214db2877cf7fa6285c22f" }, "age" : 27, "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "c" : 89, "country" : "China", "e" : 67, "email" : "2145567457@qq.com", "m" : 96, "name" : "zhangsan", "sex" : "m", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c22d" }, "age" : 25, "books" : [ "PHP", "JAVA", "EXTJS", "C++" ], "c" : 75, "country" : "USA", "e" : 97, "email" : "214557457@qq.com", "m" : 66, "name" : "tom", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c22e" }, "age" : 26, "books" : [ "JS", "JAVA", "C#", "MONGODB" ], "c" : 75, "country" : "USA", "e" : 97, "email" : "344521457@qq.com", "m" : 93, "name" : "lili", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c230" }, "age" : 27, "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ], "c" : 35, "country" : "Korea", "e" : 47, "email" : "lizhenxian@uspcat.com", "m" : 56, "name" : "lizhenxian", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c231" }, "age" : 21, "books" : [ "JS", "JAVA", "PHP", "MONGODB" ], "c" : 36, "country" : "Korea", "e" : 32, "email" : "lixiaoli@uspcat.com", "m" : 86, "name" : "lixianli", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c232" }, "age" : 22, "books" : [ "JS", "JAVA", "C#", "MONGODB" ], "c" : 45, "country" : "Korea", "e" : 77, "email" : "zhangsuying@uspcat.com", "m" : 93, "name" : "zhangsuying", "size" : 4 }
{ "_id" : { "$oid" : "53214db2877cf7fa6285c22c" }, "age" : 25, "books" : [ "JS", "C++", "EXTJS", "MONGODB", "ORACLE" ], "c" : 89, "country" : "USA", "e" : 87, "email" : "75431457@qq.com", "m" : 96, "name" : "jim", "school" : [ { "school" : "K", "score" : "A" }, { "school" : "L", "score" : "B" }, { "school" : "J", "score" : "A+" } ], "size" : 5 }
{ "_id" : { "$oid" : "5323f13e078a23f43b69fc6f" }, "name" : "USPCAT", "age" : 27, "email" : "2145567457@qq.com", "c" : 89, "m" : 100, "e" : 67, "conutry" : "China", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "_id" : { "$oid" : "5323f2e2078a23f43b69fc70" }, "name" : "USPCAT", "age" : 27, "email" : "2145567457@qq.com", "c" : 89, "m" : 100, "e" : 67, "conuTry" : "China", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }
{ "_id" : { "$oid" : "5323f41d078a23f43b69fc71" }, "name" : "USPCAT", "age" : 27, "email" : "2145567457@qq.com", "c" : 89, "m" : 100, "e" : 67, "counTry" : "China", "books" : [ "JS", "JAVA", "EXTJS", "MONGODB" ] }


#删除数据库
db.dropDatabase()


#上锁解锁
#上锁(出现权限不够的问题)
> use foobar
switched to db foobar
> db.runCommand({fsync:1,lock:1})
{ "errmsg" : "access denied; use admin db", "ok" : 0 }


#上锁时候要用admin用户,如下所示,现将其转换为admin用户
> use admin
switched to db admin


#上锁(对数据库进行上锁)
> db.runCommand({fsync:1,lock:1})
{
        "info" : "now locked against writes, use db.fsyncUnlock() to unlock",
        "seeAlso" : "http://www.mongodb.org/display/DOCS/fsync+Command",
        "ok" : 1
}


#解锁
#对数据库进行解锁(还是用admin用户进行解锁)
> db.currentOp()
{
        "inprog" : [ ],
        "fsyncLock" : 1,
        "info" : "use db.fsyncUnlock() to terminate the fsync write/snapshot loc
k"
}
>


#数据修复
db.repairDatabase()


#添加一个用户

#为admin添加uspcat用户和foobar数据库添加guanxiangqing用户

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值