install
Mac OS
1
2
3
4
5
6
7
8
9
| brew tap mongodb/brew
brew install mongodb-community@4.2
# Run
# config file: /usr/local/etc/mongod.conf
brew services start mongodb-community@4.2
$ Connect
mongo
|
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
CRUD
Create,Read,Update,Delete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| //在集合中插入一个文档,如果集合不存在,会自动创建
db.<collection>.insert()
//条件查找 - 等于
db.getCollection('movie').find({"name":"Doctor Strange"})
//条件查找 - 小于 | 大于 | 不等于 | 小于等于 | 大于等于
db.<collection>.find(
{<key>:{<$lt | $gt | $ne | $lte | $gte>:<value>}},
)
//and 查询
getCollection('movie').find({"price":19.55,"on":true})
//投影,1为要显示的字段,0为不要显示的字段
db.<collection>.find({},{"_id":0,"title":1})
//限制
db.<collection>.find().limit(2)
//跳过
db.<collection>.find().skip(2)
//排序, 1升序,-1降序 , 前面的优先级高
db.<collection>.find({}).sort({"name":1,"price":-1})
//更新所以符合条件的文档,不设置multi时默认更新单条文档
db.movie.update({"price":20.00},{$set:{"price":23.00}},{multi:true})
//覆盖原有文档
db.<collection>.save()
//删除所有符合条件的文档
db.<collection>.remove()
|
Update
更新需要使用更新操作符
$inc , $set , $unset , $currentDate …
$push , $addToSet …
Dot Notation
MongoDB uses the dot notation to access the elements of an arrary and to access the fields of an embedded document.
注意要使用双引号
1
2
3
4
| //Array - zero-based index position
"<array>.<index>"
//Embedded Documents
"<embedded document>.<field>"
|
1
2
| //从咨询记录中找出评分大于等于9.8的医生
db.consult.find({"doctor.rate":{$gte:"9.8"}})
|
$exists
1
| { field: { $exists: <boolean>} }
|
$where
Ues the $where operator to pass a string containing a JavaScript expression or a full JavaScript function to the query system.The $where provides greater flexibility, but require that database processes the JavaScript expression of function for each document in collection.
reference the document in the JavaScript expression or function using either this or obj.
1
2
| db.<collection>.find( { $where: "this.credits == this.debits"} )
db.<collection>.find( { $where: "this.name.length > 1" } )
|
$arrayElemAt
return the element at the specified array index
1
| { $arrayElemAt: [ <array>, <idx>] }
|
$regex
Aggregation
$match
1
| {"$match": {"name": "拉杆箱"}}
|
$project
1
| {"$project": {"specs.specs": 1}}
|
$group
1
2
| // 获取Aggregation数据数量
{"$group":{_id:null,count:{$sum:1}}}
|
accumulator operator
$sum, $avg
$first, $last
$max, $min
$push, $addToSet
$unwind
deconstracts an array field from the input documents to output a document for each element.
1
| { $unwind: <field path>}
|
limit & skip
1
| db.<collection>.aggregate({$limit:150},{$skip:100})
|
$replaceRoot
抽取子对象
1
2
| // 把Group后的数据提取出来
{$replaceRoot:{newRoot:"$_id"}}
|
$out
将Aggregate的结果输出到文档中
Export
使用 mongoexport
来导出文件
1
| mongoexport -d database -c results -f <field1,field2...> --csv > results.csv
|
Robo 3T
https://robomongo.org