赞
踩
mongo
显示所有数据库
show dbs
选择(或创建)数据库
db
show collections
创建集合
db.createCollection("myCollection")
删除集合
db.myCollection.drop()
插入单个文档:
db.myCollection.insertOne({name: "Alice", age: 25})
插入多个文档:
db.myCollection.insertMany([{name: "Bob", age: 30}, {name: "Charlie", age: 35}])
查询所有文档:
db.myCollection.find()
带条件查询:
db.myCollection.find({age: {$gt: 30}})
查询特定字段:
db.myCollection.find({}, {name: 1, age: 1, _id: 0})
更新单个文档:
db.myCollection.updateOne({name: "Alice"}, {$set: {age: 26}})
更新多个文档:
db.myCollection.updateMany({age: {$gt: 30}}, {$set: {status: "Senior"}})
替换文档:
db.myCollection.replaceOne({name: "Alice"}, {name: "Alice", age: 27, city: "New York"})
删除单个文档:
db.myCollection.deleteOne({name: "Alice"})
删除多个文档:
db.myCollection.deleteMany({age: {$lt: 30}})
db.myCollection.createIndex({name: 1})
显示索引
db.myCollection.getIndexes()
删除索引
db.myCollection.dropIndex("name_1")
- db.myCollection.aggregate([
- {$match: {status: "Senior"}},
- {$group: {_id: "$status", total: {$sum: 1}}}
- ])
db.dropDatabase()
- db.createUser({
- user: "myUser",
- pwd: "myPassword",
- roles: [{role: "readWrite", db: "myDatabase"}]
- })
删除用户
db.dropUser("myUser")
mongodump --db myDatabase --out /path/to/backup
数据库恢复
mongorestore /path/to/backup/myDatabase
db.serverStatus()
查看当前操作
db.currentOp()
杀死长时间运行的操作
db.killOp(opid)
db.myCollection.find({age: {$gte: 25}}, {name: 1, age: 1, _id: 0})
排序
db.myCollection.find().sort({age: -1})
分页
db.myCollection.find().skip(10).limit(10)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。