Skip to content

MongoDB 常用命令

1. 创建 DB

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

2. 创建一个集合

javascript
// 只要在该集合中插入第一条记录,即会自动创建该集合
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. 显示现有集合

bash
show collections

4. 列出集合的所有内容

javascript
db.towns.find()

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

javascript
db.towns.insert

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

MongoDB 加载自定义的 JS 脚本

7. 根据 id 查找数据

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

8. 过滤查询结果字段

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

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

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

10. 更新

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

11. 删除

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

12. 修改集合名称

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

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.