mongo-基本操作
連接
mongo mongodb://user:pass@ip:port/db
root@c87416afb49d:/# mongo mongodb://root:root@localhost:27017
數據庫操作
查看數據庫
- 查看所有數據庫
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mybatis 0.000GB
- 查看當前數據庫
> db
mybatis
3.創建數據庫
user databaseName # database沒有則創建
> use test
switched to db test
> show dbs # 剛創建時看不見test,需要向test數據庫中插入數據
admin 0.000GB
config 0.000GB
local 0.000GB
mybatis 0.000GB
> db.test.insert({name:'test'})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mybatis 0.000GB
test 0.000GB
- 刪除數據
db.dropDatabase()
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mybatis 0.000GB
集合操作
- 創建集合
db.createCollection(name, options)
> db.createCollection("users")
{ "ok" : 1 }
> show collections
message
users
- 查看集合
show collections
- 刪除集合
db.collection.drop()
> db.users.drop()
true
> show collections
message
文檔
插入文檔
db.COLLECTION_NAME.insert(document) 或 db.COLLECTION_NAME.save(document)
> db.users.insert({name:'mongo', version:'1.0'})
WriteResult({ "nInserted" : 1 })
刪除文檔
method | desc |
---|---|
db.collection.deleteOne() | 僅僅只刪除一個,儘管匹配了多個 |
db.collection.deleteMany() | 刪除多個 |
db.collection.remove() | 刪除單個或者全部 |
> db.users.remove({})
WriteResult({ "nRemoved" : 1 })
> db.users.find().pretty()
更新文檔
db.collection.update(
`<query>`,
`<update>`,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
})
根據 name 更新
> db.users.update({name:'mongo'},{$set:{time:'hello'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({}).pretty()
{
"_id" : ObjectId("5ef5b146641d4353f5d4cee5"),
"name" : "mongo",
"version" : "1.0",
"time" : "hello"
}
查詢文檔
db.collection.find(query)
> db.users.find({}).pretty()
{
"_id" : ObjectId("5ef5b146641d4353f5d4cee5"),
"name" : "mongo",
"version" : "1.0"
}