Collection操作
显示所有数据库名
show dbs;
显示数据库中所有Collection名
use {dbname};
show collections;
创建Collection
use {dbname};
db.createCollection("");
重命名Collection
db.collection.renameCollection("");
删除collection
use {dbname};
db.{collection}.drop();
删除数据库
use {dbname};
db.dropDatabase();
Document的操作
- db.{collection}.insert();
// 通过JavaScript批量插入数据
for(var i=0; i<100; i++) {
db.user.insert({
name: "user-" + i,
age : Math.floor(Math.random()*20) + 10,
team: "T" + (i%3),
});
}
- db.{collection}.find();
find()第一个参数:指定检索条件
find()第二个参数:指定是否显示指定字段(0:不显示 1:显示)
db.user.find({name:"shou"}, {_id:0}).sort({age:1}) // age升序排列
db.user.find({name:"shou"}, {_id:0}).sort({age:-1}) // age降序排列
db.user.find({name:"shou"}, {_id:0}).sort({age: 1}).skip(2) // 获取从第2条数据开始的记录
db.user.find({name:"shou"}, {_id:0}).sort({age: 1}).skip(2).limit(4) // 获取第3条记录开始的4条记录
逻辑条件运算符
| > | $gt | db.user.find({"age": {$gt: 22} }); |
| >= | $gte | db.user.find({"age": {$gte: 22} }); |
| < | $lt | db.user.find({"age": {$lt: 22} }); |
| >= | $lte | db.user.find({"age": {$lte: 22} }); |
| != | $ne | db.user.find({"age": {$ne: 22} }); |
| = | -- | db.user.find({"age": 22}); |
| And | -- | db.user.find({ "name": "shou", "age": 30 }); |
| Or | $or | db.user.find({ $or: [{"name": "shou"}, {"name": "ko"}] }); |
| IN | $in | db.user.find({ "name": {$in: ["shou", "ko"]} }); |
| notin | $nin | db.user.find({ "name": {$nin: ["shou", "shou31"]} }) |
AND
db.user.find({
$and: [
{team: "T0"},
{age: {$lt: 50}}
]
})
OR
db.user.find({
$or: [
{team: {$in: ["T0", "T1"]}},
{age: {$exists: true}}
]
})
DISTINCT
db.user.distinct("team")
正则表达式
db.user.find({"name": /^s/, "name": /2$/});
db.user.find({"name": /user-[1-3]/});
$where表达式
db.user.find({$where: function(){ return this.name == "shou" }});
db.{collection}.update();
局部更新:
inc:increase的缩写,增加指定字段的值 set : 只更新指定的字段的值
db.user.update({“name”: “ko”}, {$set: {“age” : 21}})upsert操作:
将update的第三个参数设为true即可。批量更新 :
在mongodb中如果匹配多条,默认的情况下只更新第一条。
那么如果我们有需求必须批量更新, 将update的第四个参数设置为 true 即可。db.{collection}.remove();
db.{collection}.count();
索引(Index)
- 一览:db.{collection}.getIndexes();
- 追加:db.{collection}.ensureIndex();
- 删除:db.{collection}.dropIndex();
db.user.ensureIndex({age: 1});
db.user.dropIndex({age:1}) //
db.user.ensureIndex({age: 1}, {unique: true}); // 唯一索引
db.user.update({name:”user-1”}, {$unset:{age:”“}]}) // 删除该记录中的age字段
db.user.update({name:”user-2”}, {$inc:{age:5}]}) // 将age字段的值加5
db.user.update({name:”user-2”}, {$inc:{age: -10}]}) // 将age字段的值减10
db.user.update({name:”user-2”}, {$rename:{age: “newage”}}) // 将 age 的名字改为 newage