以下对数据库的查询、添加、更新、删除等操作
注意:需要排照顺序来操作下面语句,表即文档集合
=========================================================
E:\J2EE_SOFTWARE\mongodb\bin>mongo 127.0.0.1:27017/admin
MongoDB shell version: 2.4.9
connecting to: 127.0.0.1:27017/admin
Welcome to the MongoDB shell.
#创建数据库cyjch/或是切换数据库
> use cyjch
switched to db cyjch
#显示数据库列表
> show dbs
cyjch 0.203125GB
local 0.078125GB
#创建user并添加一列数据
> db.user.insert({name:"jichao"})
#显示数据库表(即collections)
> show collections
user
system.indexes
#查看user表中的数据
> db.user.find()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jichao" }
#查看user表中的第一条数据
> db.user.findOne()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jichao" }
#查询表中总记录数
1)查询map表中gis属性为x=50,y=50的记录数量
> db.map.find({gis:{x:50,y:50}}).count()
2
2)请查询persons中美国学生的人数.
>db.persons.find({country:"USA"}).count()
#去重Distinct
请查询出persons表中一共有多少个国家分别是什么.
>db.runCommand({distinct:"persons“ , key:"country"}).values
["China","USA","Korea"]
#Group
语法:
db.runCommand({group:{
ns:集合名字,
Key:分组的键对象,
Initial:初始化累加器,
$reduce:组分解器,
Condition:条件,
Finalize:组完成器
}})
分组首先会按照key进行分组,每组的 每一个文档全要执行$reduce的方法,
他接收2个参数一个是组内本条记录,一个是累加器数据.
请查出persons中每个国家学生数学成绩最好的学生信息(必须在90以上)
db.runCommand({
group:{
#集合名字,namespace
ns:"persons",
#分组的键对象
key:{
"country":true
},
#初始化数学成绩
initial:{
m:0
},
#分析器,如果大于90分的保存,最终保存的是最高成绩的学生
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
#条件m大于90(数学大于90分)
condition:{
m:{
$gt:90
}
}
}
})
要求以上基础之上把没个人的信息链接起来写一个描述赋值到m上
db.runCommand({
group:{
#集合名字,namespace
ns:"persons",
#分组的键对象
key:{
"country":true
},
#初始化数学成绩
initial:{
m:0
},
#分析器,如果大于90分的保存,最终保存的是最高成绩的学生
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
#条件m大于90(数学大于90分)
condition:{
m:{
$gt:90
}
},
#组完成器
finalize:function(prev){
prev.m = prev.name+" Math scores "+prev.m
}
}
})
#更新局部数据user表中的数据
> db.user.update({name:"jichao"},{$set:{name:"jc"}})
> db.user.find()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jc" }
#强硬更新数据user表中的数据,将会用新表替换旧表
> db.user.insert({_id:1,name:"cyjch",age:32})
> db.user.find()
{ "_id" : 1, "name" : "cyjch", "age" : 32 }
> db.user.update({name:"cyjch"},{age:30})
> db.user.find()
{ "_id" : 1, "age" : 30 }
#更新或增加操作(insertOrUpdate),有则更新,无则增加
> db.user.update({_id:2},{_id:2,name:"chao"},true)
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "chao" }
#批量更新,$set为修改器,第一个参数false:不更新或插入操作,第二个参数true:批量更新操作
> db.user.insert({_id:3,name:"chao"})
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "chao" }
{ "_id" : 3, "name" : "chao" }
> db.user.update({name:"chao"},{$set:{name:"cc"}},false,true)
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "cc" }
{ "_id" : 3, "name" : "cc" }
#删除表中的数据(按条件)
>db.user.remove({id:1})
#删除表中的所有数据,但索引不会被删除
> db.user.remove()
#删除user表
> db.user.drop()
true
#删除cyjch库
> db.dropDatabase()
{ "dropped" : "cyjch", "ok" : 1 }
> show dbs
local 0.078125GB
#MONGDB的shell内置javascript引擎可以直接执行JS代码
> function insert(object){
db.user.insert(object)
}
> insert({id:2,name:"jichao2"})
#可以在一个集合中的文档嵌入多个子文档
> db.user.insert({id:3,name:"jichao3",child:{name:"cyjch"}})
> db.user.find()
{ "_id" : ObjectId("52dfcde384e4fb490680facc"), "id" : 1, "name" : "jichao" }
{ "_id" : ObjectId("52dfd04984e4fb490680facd"), "id" : 2, "name" : "jichao2" }
{ "_id" : ObjectId("52dfd28884e4fb490680face"), "id" : 3, "name" : "jichao3", "child" : { "name" : "cyjch" } }
>
#批量插入数据
> for(var i=4;i<10;i++){
... db.user.insert({id:i,name:"jichao"+i});
... }
> db.user.find()
> db.user.find()
{ "_id" : ObjectId("52dfcde384e4fb490680facc"), "id" : 1, "name" : "jichao1" }
{ "_id" : ObjectId("52dfd04984e4fb490680facd"), "id" : 2, "name" : "jichao2" }
{ "_id" : ObjectId("52dfd28884e4fb490680face"), "id" : 3, "name" : "jichao3", "child" : { "name" : "cyjch1" } }
{ "_id" : ObjectId("52dfd76d84e4fb490680facf"), "id" : 4, "name" : "jichao4" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad0"), "id" : 5, "name" : "jichao5" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad1"), "id" : 6, "name" : "jichao6" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad2"), "id" : 7, "name" : "jichao7" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad3"), "id" : 8, "name" : "jichao8" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad4"), "id" : 9, "name" : "jichao9" }
#insert与save的区别:insert相同的_id值时会报错,而save()可以更新存在的值
> db.user.insert({_id:10,name:"temp"})
> db.user.find({_id:10})
{ "_id" : 10, "name" : "temp" }
> db.user.insert({_id:10,name:"temp"})
E11000 duplicate key error index: cyjch.user.$_id_ dup key: { : 10.0 }
> db.user.save({_id:10,name:"tmp"})
> db.user.find({_id:10})
{ "_id" : 10, "name" : "tmp" }
#可以执行js的eval()
> db.eval("return 'mongodb'")
mongodb
>
#获取当前数据库名称
> db.getName()
cyjch
#获取数据库当前状态
> db.stats()
{
"db" : "cyjch",
"collections" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"nsSizeMB" : 0,
"dataFileVersion" : {
},
"ok" : 1
}
#查询帮助
> db.help()
DB methods:
db.addUser(userDocument)
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ 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.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval(func, args) run code server-side
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.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 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.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.removeUser(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.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
>
#集合(表)的帮助
> db.user.help()
DBCollection help
db.user.find().help() - show DBCursor help
db.user.count()
db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command
db.user.dataSize()
db.user.distinct( key ) - e.g. db.user.distinct( 'x' )
db.user.drop() drop the collection
db.user.dropIndex(index) - e.g. db.user.dropIndex( "indexName" ) ordb.user.dropIndex( { "indexKey" : 1 } )
db.user.dropIndexes()
db.user.ensureIndex(keypattern[,options]) - options is an object withthese possible fields: name, unique, dropDups
db.user.reIndex()
db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.e.g. db.user.find( {x:77} , {name:1, x:1} )
db.user.find(...).count()
db.user.find(...).limit(n)
db.user.find(...).skip(n)
db.user.find(...).sort(...)
db.user.findOne([query])
db.user.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
db.user.getDB() get DB object associated with collection
db.user.getIndexes()
db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] })
db.user.insert(obj)
db.user.mapReduce( mapFunction , reduceFunction , <optional params> )
db.user.remove(query)
db.user.renameCollection( newName , <dropTarget> ) renames the collection.
db.user.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.user.save(obj)
db.user.stats()
db.user.storageSize() - includes free space allocated to this collection
db.user.totalIndexSize() - size in bytes of all the indexes
db.user.totalSize() - storage allocated for all data and indexes
db.user.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
db.user.validate( <full> ) - SLOW
db.user.getShardVersion() - only for use with sharding
db.user.getShardDistribution() - prints statistics about data distribution in the cluster
db.user.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
>
注意:需要排照顺序来操作下面语句,表即文档集合
=========================================================
E:\J2EE_SOFTWARE\mongodb\bin>mongo 127.0.0.1:27017/admin
MongoDB shell version: 2.4.9
connecting to: 127.0.0.1:27017/admin
Welcome to the MongoDB shell.
#创建数据库cyjch/或是切换数据库
> use cyjch
switched to db cyjch
#显示数据库列表
> show dbs
cyjch 0.203125GB
local 0.078125GB
#创建user并添加一列数据
> db.user.insert({name:"jichao"})
#显示数据库表(即collections)
> show collections
user
system.indexes
#查看user表中的数据
> db.user.find()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jichao" }
#查看user表中的第一条数据
> db.user.findOne()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jichao" }
#查询表中总记录数
1)查询map表中gis属性为x=50,y=50的记录数量
> db.map.find({gis:{x:50,y:50}}).count()
2
2)请查询persons中美国学生的人数.
>db.persons.find({country:"USA"}).count()
#去重Distinct
请查询出persons表中一共有多少个国家分别是什么.
>db.runCommand({distinct:"persons“ , key:"country"}).values
["China","USA","Korea"]
#Group
语法:
db.runCommand({group:{
ns:集合名字,
Key:分组的键对象,
Initial:初始化累加器,
$reduce:组分解器,
Condition:条件,
Finalize:组完成器
}})
分组首先会按照key进行分组,每组的 每一个文档全要执行$reduce的方法,
他接收2个参数一个是组内本条记录,一个是累加器数据.
请查出persons中每个国家学生数学成绩最好的学生信息(必须在90以上)
db.runCommand({
group:{
#集合名字,namespace
ns:"persons",
#分组的键对象
key:{
"country":true
},
#初始化数学成绩
initial:{
m:0
},
#分析器,如果大于90分的保存,最终保存的是最高成绩的学生
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
#条件m大于90(数学大于90分)
condition:{
m:{
$gt:90
}
}
}
})
要求以上基础之上把没个人的信息链接起来写一个描述赋值到m上
db.runCommand({
group:{
#集合名字,namespace
ns:"persons",
#分组的键对象
key:{
"country":true
},
#初始化数学成绩
initial:{
m:0
},
#分析器,如果大于90分的保存,最终保存的是最高成绩的学生
$reduce:function(doc,prev){
if(doc.m > prev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
#条件m大于90(数学大于90分)
condition:{
m:{
$gt:90
}
},
#组完成器
finalize:function(prev){
prev.m = prev.name+" Math scores "+prev.m
}
}
})
#更新局部数据user表中的数据
> db.user.update({name:"jichao"},{$set:{name:"jc"}})
> db.user.find()
{ "_id" : ObjectId("52dfc44184e4fb490680facb"), "name" : "jc" }
#强硬更新数据user表中的数据,将会用新表替换旧表
> db.user.insert({_id:1,name:"cyjch",age:32})
> db.user.find()
{ "_id" : 1, "name" : "cyjch", "age" : 32 }
> db.user.update({name:"cyjch"},{age:30})
> db.user.find()
{ "_id" : 1, "age" : 30 }
#更新或增加操作(insertOrUpdate),有则更新,无则增加
> db.user.update({_id:2},{_id:2,name:"chao"},true)
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "chao" }
#批量更新,$set为修改器,第一个参数false:不更新或插入操作,第二个参数true:批量更新操作
> db.user.insert({_id:3,name:"chao"})
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "chao" }
{ "_id" : 3, "name" : "chao" }
> db.user.update({name:"chao"},{$set:{name:"cc"}},false,true)
> db.user.find()
{ "_id" : 1, "age" : 30 }
{ "_id" : 2, "name" : "cc" }
{ "_id" : 3, "name" : "cc" }
#删除表中的数据(按条件)
>db.user.remove({id:1})
#删除表中的所有数据,但索引不会被删除
> db.user.remove()
#删除user表
> db.user.drop()
true
#删除cyjch库
> db.dropDatabase()
{ "dropped" : "cyjch", "ok" : 1 }
> show dbs
local 0.078125GB
#MONGDB的shell内置javascript引擎可以直接执行JS代码
> function insert(object){
db.user.insert(object)
}
> insert({id:2,name:"jichao2"})
#可以在一个集合中的文档嵌入多个子文档
> db.user.insert({id:3,name:"jichao3",child:{name:"cyjch"}})
> db.user.find()
{ "_id" : ObjectId("52dfcde384e4fb490680facc"), "id" : 1, "name" : "jichao" }
{ "_id" : ObjectId("52dfd04984e4fb490680facd"), "id" : 2, "name" : "jichao2" }
{ "_id" : ObjectId("52dfd28884e4fb490680face"), "id" : 3, "name" : "jichao3", "child" : { "name" : "cyjch" } }
>
#批量插入数据
> for(var i=4;i<10;i++){
... db.user.insert({id:i,name:"jichao"+i});
... }
> db.user.find()
> db.user.find()
{ "_id" : ObjectId("52dfcde384e4fb490680facc"), "id" : 1, "name" : "jichao1" }
{ "_id" : ObjectId("52dfd04984e4fb490680facd"), "id" : 2, "name" : "jichao2" }
{ "_id" : ObjectId("52dfd28884e4fb490680face"), "id" : 3, "name" : "jichao3", "child" : { "name" : "cyjch1" } }
{ "_id" : ObjectId("52dfd76d84e4fb490680facf"), "id" : 4, "name" : "jichao4" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad0"), "id" : 5, "name" : "jichao5" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad1"), "id" : 6, "name" : "jichao6" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad2"), "id" : 7, "name" : "jichao7" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad3"), "id" : 8, "name" : "jichao8" }
{ "_id" : ObjectId("52dfd76d84e4fb490680fad4"), "id" : 9, "name" : "jichao9" }
#insert与save的区别:insert相同的_id值时会报错,而save()可以更新存在的值
> db.user.insert({_id:10,name:"temp"})
> db.user.find({_id:10})
{ "_id" : 10, "name" : "temp" }
> db.user.insert({_id:10,name:"temp"})
E11000 duplicate key error index: cyjch.user.$_id_ dup key: { : 10.0 }
> db.user.save({_id:10,name:"tmp"})
> db.user.find({_id:10})
{ "_id" : 10, "name" : "tmp" }
#可以执行js的eval()
> db.eval("return 'mongodb'")
mongodb
>
#获取当前数据库名称
> db.getName()
cyjch
#获取数据库当前状态
> db.stats()
{
"db" : "cyjch",
"collections" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"nsSizeMB" : 0,
"dataFileVersion" : {
},
"ok" : 1
}
#查询帮助
> db.help()
DB methods:
db.addUser(userDocument)
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ 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.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval(func, args) run code server-side
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.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 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.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.removeUser(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.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
>
#集合(表)的帮助
> db.user.help()
DBCollection help
db.user.find().help() - show DBCursor help
db.user.count()
db.user.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
db.user.convertToCapped(maxBytes) - calls {convertToCapped:'user', size:maxBytes}} command
db.user.dataSize()
db.user.distinct( key ) - e.g. db.user.distinct( 'x' )
db.user.drop() drop the collection
db.user.dropIndex(index) - e.g. db.user.dropIndex( "indexName" ) ordb.user.dropIndex( { "indexKey" : 1 } )
db.user.dropIndexes()
db.user.ensureIndex(keypattern[,options]) - options is an object withthese possible fields: name, unique, dropDups
db.user.reIndex()
db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.e.g. db.user.find( {x:77} , {name:1, x:1} )
db.user.find(...).count()
db.user.find(...).limit(n)
db.user.find(...).skip(n)
db.user.find(...).sort(...)
db.user.findOne([query])
db.user.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
db.user.getDB() get DB object associated with collection
db.user.getIndexes()
db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] })
db.user.insert(obj)
db.user.mapReduce( mapFunction , reduceFunction , <optional params> )
db.user.remove(query)
db.user.renameCollection( newName , <dropTarget> ) renames the collection.
db.user.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.user.save(obj)
db.user.stats()
db.user.storageSize() - includes free space allocated to this collection
db.user.totalIndexSize() - size in bytes of all the indexes
db.user.totalSize() - storage allocated for all data and indexes
db.user.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
db.user.validate( <full> ) - SLOW
db.user.getShardVersion() - only for use with sharding
db.user.getShardDistribution() - prints statistics about data distribution in the cluster
db.user.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
>
================================================
原文:http://blog.csdn.net/cyjch/article/details/51750181
作者:超越
超越的主页:http://blog.csdn.net/cyjch
================================================