MongoDB入门笔记

环境

MacOS10.14.4

安装

brew tap mongodb/brew
brew install mongodb-community@4.0

运行

in the foreground

mongod --config /usr/local/etc/mongod.conf

as a macOS service

brew services start mongodb-community@4.0

连接并使用

mongo

基本操作

Create 增

插入一个

db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

插入多个

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

Read 查

查询单个

db.inventory.find( { item: "canvas" } )

查询所有

db.inventory.find( {} )

利用操作符指定查询条件

db.inventory.find( { status: { $in: [ "A", "D" ] } } )
含义等价于
SELECT * FROM inventory WHERE status in ("A", "D")

AND

db.inventory.find( { status: "A", qty: { $lt: 30 } } )
含义等价于
SELECT * FROM inventory WHERE status = "A" AND qty < 30

OR

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
含义等价于
SELECT * FROM inventory WHERE status = "A" OR qty < 30

AND OR

db.inventory.find( {
     status: "A",
     $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
含义等价于
SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

Update 改

update one

db.inventory.updateOne(
   { item: "paper" },
   {
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true }
   }
)

update many

db.inventory.updateMany(
   { "qty": { $lt: 50 } },
   {
     $set: { "size.uom": "in", status: "P" },
     $currentDate: { lastModified: true }
   }
)

replace one

db.inventory.replaceOne(
   { item: "paper" },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)

Delete 删

delete all

db.inventory.deleteMany({})

delete many

db.inventory.deleteMany({ status : "A" })

delete one

db.inventory.deleteOne( { status: "D" } )

参考链接

原文地址:https://www.cnblogs.com/luoxiaolei/p/11278118.html