Mongodb基本操作:insert & update

Author Avatar
高宇哲 3月 26, 2017

Insert & Update

insert

mongodb insert的方式

db.log.insert({
    編號: 4,
    書本資料: "超人氣台灣美食",
    價錢: 250,
    借閱人: "小華",
    借閱時間: ISODate("2015-07-30T22:30:30:00Z")
})

update

mongodb update的方式

db.log.update({
    書本資料:"超人氣台灣美食"
}, {
    $set:{"借閱人": "高宇哲"}
})

Field Update Operators

Reference: https://docs.mongodb.com/manual/reference/operator/update-field/

batch insert

mongodb需要大量insert時的方式

db.user.remove({})
db.user.insert([
    {_id:"001", name:"小明", balance:1500},
    {_id:"002", name:"小高", balance:3000},
    {_id:"003", name:"小華", balance:4500},
    {_id:"004", name:"小花", balance:1500},
    {_id:"005", name:"魔人啾啾", balance:1800}
])

$inc operator

使用$inc運算子對某欄位增加一特定值,其格式為

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

Example:

db.user.update({
    name: "小明"
}, {
    $inc: {balance:-1000}
})

$set operator

db.user.update({
    name: "小明"
}, {
    $set: {balance:1500}
})

$unset operator

使用$unset運算子刪除部分欄位,其格式如下:

{ $unset: { <field1>: "", ... } }

Example:

db.user.update({
    name: "小明"
}, {
    $unset:{balance:""}
})

案例

Question:將以下資料的UST改成NTD, price乘以31.4

{ _id: "001", product: "Sony, SBH60", type: "USD", price: 76.4 },
{ _id: "002", product: "Sony, SBH70", type: "USD", price: 75.8 },
{ _id: "003", product: "Sony, SBH80", type: "NTD", price: 2980 }

Ans

use product
db.list.remove({})
db.list.insert([
    { _id: "001", product: "Sony, SBH60", type: "USD", price: 76.4 },
    { _id: "002", product: "Sony, SBH70", type: "USD", price: 75.8 },
    { _id: "003", product: "Sony, SBH80", type: "NTD", price: 2980 }
])

db.list.update({
    type:"USD"
}, {
    $mul: {price:31.4},
    $set: {type:"NTD"}
}, {
    multi: true
})

Array Update Operator

$push operator

use product
db.serial.remove({})
db.serial.insert({
    _id: "001", list: [30, 40, 50]
})

db.serial.update({
    _id: "001"
}, {
    $push: {list: 80}
})

db.serial.update({
    _id: "001"
}, {
    $push: {list: 80}
})

db.serial.update({
    _id: "001"
}, {
    $push: {
        list:{$each: [70], $position: 3}
    }
})