基本操作
1. 查询当前实例的数据库
show dbs
2. 切换到指定的数据库
use dbname
3.获取当前库的集合
show collections
4.获取某个集合的索引
db.users.getIndexes()
批量插入数据
for(i=0;i<20000;i++){
db.numbers.save({num:i})
}
5.创建索引
db.numbers.createIndex({num:1})
6.范围查询
db.numbers.find({num:{$gt:20,$lt:30}});
7.获取执行计划
db.numbers.find({num:{$gt:19995}}).explain("executionStats");
8获取当前数据库的状态
db.stats()
{
"db" : "tutorial",
"collections" : 2,
"views" : 0,
"objects" : 20001,
"avgObjSize" : 35.00464976751162,
"dataSize" : 700128,
"storageSize" : 389120,
"numExtents" : 0,
"indexes" : 3,
"indexSize" : 462848,
"fsUsedSize" : 10720202752,
"fsTotalSize" : 42139451392,
"ok" : 1
}
获取帮助命令
help
db.help()
mongo --help 获取登陆shell的帮助
增
- 插入数据
db.users.insert({username:“smith”})
db.users.insert({username:“jones”})
改
- 所有的修改文档都需要2个参数,第一个参数指定要更新的文档,第二个定义如何修改此文档。
- 默认update只更新一个文档
- 通常有两种类型的更新操作
- 只更新文档的部分字段,这种方式需要传递$set操作符
- 使用新文档替换原来的文档
smith文档增加country字段
db.users.update(
{username:"smith"},
{$set: {country:"canada"}
})
替换更新:将smith文档替换为country;替换文档_id的字段的值不会改变
db.users.update(
{username:"smith"},
{country:"canada"}
)
$unset 删除文档的某个字段
db.users.update(
{username:"smith"},
{ $unset: {country:1} }
)
复杂的修改
db.users.update(
{username:"smith"},
{$set:{
favorites:{
cities:["chicago", "cheyenne" ],
movies:["casablanca","for a few dollars more","the string"]
}
}
})
db.users.update( {username:"jones"},
{$set:{
favorites :{
movies: ["casablanca","rocky"]
}
}
}
)
db.users.find().pretty()格式化显示查询结果
高级更新
所有喜欢casablanca的人,也喜欢the maltest falcon电影
db.users.update( {"favorites.movies":"casablanca"},
{$addToSet: { "favorites.movies":"the maltest falcon"}},
false,
true)
第一个参数是查询条件
第二个参数使用$addToSet 将the maltest falcon 添加到列表中
第三个参数false ,控制是否允许upsert,告诉更新操作,当文档不存在时是否执行插入操作
第四个参数true,是否是多个更新,默认情况下mongo只更新第一个匹配文旦
查
查询集合的所有数据
db.users.find()
{ "_id" : ObjectId("5d176f1db96688f9c1569740"), "username" : "smith" }
查询集合中文档的个数
db.users.count()
条件查询
db.users.find({username:"smith"})
多条件查询,多条件 AND查询
db.users.find({_id:ObjectId("5d176f1db96688f9c1569740"),username:"smith"})
也可以使用$and操作符
db.users.find({
$and:[
{ _id : ObjectId("5d176f1db96688f9c1569740")},
{username : "smith"}
]
})
或条件查询 $or
db.users.find ({
$or: [
{username:"smith"},
{username:"jones"}
]
})
复杂查询 查询喜欢casablanca电影的用户
db.users.find({"favorites.movies":"casablanca"})
删
db.users.remove()删除所有的文档
db.users.remove({"favorites.cities":"cheyenne"}) 条件删除
db.users.drop() 删除整个集合
查看命令的源码
db.runCommand命令可以间接的调用shell命令;
例如:
db.runCommand({dbstats:1}) 等价于db.stats()
db.runCommand({collstats:“numbers”}) 等价于 db.numbers.stats();
去掉命令后面的()就可查看命令的源码
如
db.runCommand
function (obj, extra, queryOptions) {
"use strict";
// Support users who call this function with a string commandName, e.g.
// db.runCommand("commandName", {arg1: "value", arg2: "value"}).
var mergedObj = this._mergeCommandOptions(obj, extra);
// if options were passed (i.e. because they were overridden on a collection), use them.
// Otherwise use getQueryOptions.
var options =
(typeof(queryOptions) !== "undefined") ? queryOptions : this.getQueryOptions();
try {
return this._runCommandImpl(this._name, mergedObj, options);
} catch (ex) {
// When runCommand flowed through query, a connection error resulted in the message
// "error doing query: failed". Even though this message is arguably incorrect
// for a command failing due to a connection failure, we preserve it for backwards
// compatibility. See SERVER-18334 for details.
if (ex.message.indexOf("network error") >= 0) {
throw new Error("error doing query: failed: " + ex.message);
}
throw ex;
}
}
> db.stats
function (scale) {
return this.runCommand({dbstats: 1, scale: scale});
}
> db.numbers.save
function (obj, opts) {
if (obj == null)
throw Error("can't save a null");
if (typeof(obj) == "number" || typeof(obj) == "string")
throw Error("can't save a number or string");
if (typeof(obj._id) == "undefined") {
obj._id = new ObjectId();
return this.insert(obj, opts);
} else {
return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts));
}
}