MongoDB 常用命令

1. 创建 DB

// 创建名为book的新数据库
mongo book
  

2. 创建一个集合

// 只要在该集合中插入第一条记录,即会自动创建该集合
db.towns.insert({
    name:"New York",
    population: 22200000,
    last_census:ISODate("2009-07-31"),
    famous_for: ["status of liberty", "food"],
    mayor_info: {
        name: "Michael Bloomberg",
        party: "I"
    }
});
  

3. 显示现有集合

show collections
  

4. 列出集合的所有内容

db.towns.find()
  

5. 通过不带参数和圆括号的调用来查看源代码

db.towns.insert
  

6. 也可以创建自己的 js 函数

MongoDB 加载自定义的 JS 脚本

7. 根据 id 查找数据

db.towns.find({"_id": ObjectId("56f5ed3569e8fd6ca32b39c1")})
  

8. 过滤查询结果字段

db.towns.find({"_id": ObjectId("56f5ed3569e8fd6ca32b39c1")}, {"name":1})
  

9. 使用条件操作符查询 { $op : value}

// 查询人口小于 10000 的城市
db.towns.find({population: {$lt: 10000}}, {"name":1, population: 1})
  

10. 更新

// 不要漏掉$set 操作,否则会导致整条记录被替换
db.towns.update({"_id": ObjectId("56f5ed3569e8fd6ca32b39c1")}, { $set : { "state" : "OR" }})
  

11. 删除

// 推荐使用 find 来验证之后再删除
var where_new_york = {name: "New York"}
db.towns.find(where_new_york)
db.towns.remove(where_new_york)
  

12. 修改集合名称

> show collections
towns
> db.towns.renameCollection('cities')
{ "ok" : 1 }
> show collections
cities