1. 程式人生 > 程式設計 >MongoDB基本知識和操作掃盲!

MongoDB基本知識和操作掃盲!

MongoDB學習筆記—updating

json可以為我們描述多種關係:一對一、一對多、多對一和多對多

與js語法類似

建立記錄會自動生成一條_id主鍵,唯一id,代表該Object,也可以宣告為自定義的資料

{_id:"123"}

BSON和JSON

我們都知道Mongodb儲存的是BSON格式資料,BSON格式資料以二進位制格式儲存,可以巢狀檔案和陣列,增加了資料型別,Date,相比JSON的字串儲存,因為是二進位制儲存,不需要序列化,可以直接網路傳輸

優點:

  • 輕量
  • 可遍歷(不儲存字串,可直接通過索引獲取
  • 高效(無需序列化)
  • 增加了額外的資料型別

缺點:

  • 空間消耗多(一個整數BSON 4位元組,JSON 1位元組)

下面是JSON:

  "_id": 1,"name" : { "first" : "John","last" : "Backus" },"contribs" : [ "Fortran","ALGOL","Backus-Naur Form","FP" ],"awards" : [
    {
      "award" : "W.W. McDowell Award","year" : 1967,"by" : "IEEE Computer Society"
    },{
      "award" : "Draper Prize","year" : 1993,"by" : "National Academy of Engineering"
    }
  ]
}複製程式碼

下面兩個是BSON

{
    title:"MongoDB",    last_editor:"192.168.1.122",    last_modified:new Date("27/06/2011"),    body:"MongoDB introduction",    categories:["Database","NoSQL","BSON"],    revieved:false
}

{
    name:"lemo",    age:"12",    address:{
        city:"suzhou",        country:"china",        code:215000
    },    scores:[
        {"name":"english","grade:3.0},        {"name":"chinese","grade:2.0}
    ]
}複製程式碼

命令列

  • mongod 是用來連線到mongodb資料庫伺服器的,即伺服器端。
  • mongo 是用來啟動MongoDB shell的,是mongodb的命令列客戶端。

常用操作

  • use db_name 切換db
  • show dbs 檢視所有db
  • show collections 檢視當前db所有collections
  • db 檢視當前db

  • db.collection.insert 插入資料
  • db.collection.insertOne 插入一條資料
  • db.collection.insertMany 插入多條資料
db.people.insertOne(
   { user_id: "bcd001",age: 45,status: "A" }
)
等價:
INSERT INTO people(user_id,age,status) VALUES ("bcd001",45,"A")複製程式碼

  • db.collection.find() 查詢
  • db.collection.findOne() 檢視一個
  • db.collection.find().limit() 查詢限制條數
  • db.collection.find().count() 返回找到資料條數
db.people.find(
    { status: "A" }
)
等價:SELECT * FROM people WHERE status = "A"複製程式碼

  • 投影

查詢結果的顯示哪些資料 select 投影欄位 from collections

find({},{投影結果資料})

db.people.find(

{ },

{ userid: 1,status: 1,id: 0 }

)

等價:SELECT user_id,status FROM people

  • update() 替換 通過$set更換某一屬性值
  • db.collection.updateOne() 更新符合條件第一條
  • db.collection.updateMany() 更新符合條件的所有
  • db.collection.replaceOne() 替換符合條件的一條(所有屬性)

db.getCollection('user').update({name:"zfb"},{$set:{name:"dx",age:"12"}})

  • unset刪除一個屬性
  • db.collection.remove({})全刪除(一個一個) 應該使用db.collections.drop(),直接刪除,效率更高
  • db.collection.remove() 一個或者多個,通過設定第二個引數為true則刪除一個
  • db.collection.deleteOne() 刪除一條符合條件
  • db.collection. deleteMany() 刪除所有符合條件
  • db.dropDatabase() 刪除db,謹慎使用

db.getCollection('user').remove({name:"wgy"},true)

過濾器

  • $lt 少於
db.people.find(
   { age: { $lt: 25 } }
)
等價:
SELECT * FROM people WHERE age < 25複製程式碼

  • $gt 大於
db.people.find(
   { age: { $gt: 25 } }
)
等價:
SELECT * FROM people WHERE age > 25複製程式碼

  • $lte less than equal 小於等於
db.people.find(
   { age: { $gt: 25,$lte: 50 } }
)
等價:
SELECT * FROM people WHERE age > 25 AND   age <= 50複製程式碼

  • $regex /關鍵字/ 模糊查詢
db.people.find( { user_id: /bc/ } )
等價:
db.people.find( { user_id: { $regex: /bc/ } } )
等價:
SELECT * FROM people WHERE user_id like "%bc%"

db.people.find( { user_id: /bc^/ } )
等價:
db.people.find( { user_id: { $regex: /bc^/ } } )
等價:
SELECT * FROM people WHERE user_id like "%bc"複製程式碼

  • $exists 存在某個屬性
db.people.count( { user_id: { $exists: true } } )
等價:
SELECT COUNT(user_id) FROM people複製程式碼

  • $and 條件and連線
db.inventory.find( { $and: [ { price: { $ne: 1.99 } },{ name: "dx"  } ] } )
等價:
select * from user where price!=1.99 and name="dx"複製程式碼

  • $or 條件或連線,與and對應
  • $ne 不等於某個值的記錄
db.user.find( { qty: { $ne: 20 } } )
等價:
select * form user where qtf!=20複製程式碼

常用方法

  • explain() 解釋某條sql
db.people.find( { status: "A" } ).explain()
等價:
EXPLAIN SELECT * FROM people WHERE status = "A"複製程式碼

  • skip() 跳過指定條數記錄
db.people.find().limit(5).skip(10)
等價:
SELECT * FROM people LIMIT 5 SKIP 10複製程式碼

  • distinct()去重
db.people.distinct( "status" )
等價:
SELECT DISTINCT(status) FROM people複製程式碼

  • count()
  • limit()
  • sort() 下面索引部分

索引

排序

索引可以用於排序sort()

1升 -1降

find().sort({user_id:1})根據user_id升序排序

建立索引

db.collection.createIndex( { name: -1 } )

SpringBoot—MongoTemplate

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>複製程式碼

  • MongoTemplate
  • MongoRepository

參考博文:

https://blog.lqdev.cn/2018/11/01/springboot/chapter-thirty-one/