MongoDB 創建數據庫和查詢數據


1.選擇數據庫
  use test
 
2.創建用戶
  db.createUser({user:"test01",pwd:"12345",roles:[{role:"dbOwner",db:"test"}]});
 
3.創建數據庫   
> use sdata
switched to db sdata

4.展示數據庫(新創建的數據庫不顯示,因為數據庫里沒有數據)
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

5.使用數據庫
> use sdata
switched to db sdata

6.查看當前數據庫
> db
sdata

7.往數據庫中插入一條信息
> db.site.insert({"name":"今天測試"})
WriteResult({ "nInserted" : 1 })

8.再次顯示所有數據庫(新建的數據庫已經存在)
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
sdata   0.000GB
test    0.000GB

9.在插入一條數據
db.site.insert({"language":"Chinese"})


10.查詢數據
db.site.find().pretty()   db.表名.find()查詢數據
{ "_id" : ObjectId("5de479826829d245aa1eb134"), "name" : "今天測試" }
{
    "_id" : ObjectId("5de47a616829d245aa1eb135"),
    "name" : "今天測試",
    "age" : "30"
}
{ "_id" : ObjectId("5de47b756829d245aa1eb136"), "language" : "Chinese" }



11.按條件查詢
db.site.find({"name":"今天測試"})
> db.site.find({"name":"今天測試"})
{ "_id" : ObjectId("5de479826829d245aa1eb134"), "name" : "今天測試" }
{ "_id" : ObjectId("5de47a616829d245aa1eb135"), "name" : "今天測試", "age" : "30" }

如果希望顯示的數據格式化顯示,則使用pretty()
db.site.find({"name":"今天測試"}).pretty()
{ "_id" : ObjectId("5de479826829d245aa1eb134"), "name" : "今天測試" }
{
    "_id" : ObjectId("5de47a616829d245aa1eb135"),
    "name" : "今天測試",
    "age" : "30"
}

12.查詢條件
$lt 小於 例如{"age": {$lt:30}}
$lte 小於或等於 例如 {"age": {$lte: 30}}
$gt 大於 例如{"age": {$gt: 30}}
$gte 大於或等於
$ne 不等於
$or 邏輯或

13.查詢表中一共有多少條數據 使用.count() 方法
> db.site.find().count()
3

14.查詢一條記錄
> db.site.findOne()
{ "_id" : ObjectId("5de479826829d245aa1eb134"), "name" : "今天測試" }
>


15.如果想查詢並刪除某條數據可以使用 findOneAndDelete()
同樣的如果不指定條件的話 默認刪除表中的第一條數據
例如:
db.site.findOneAndDelete()
 
指定條件
db.site.findOneAndDelete({"age": "30"})



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM