Source: MongoDB University https://university.mongodb.com/
Course: M001 MongoDB bascis
【Chapter 5】: Indexing and Aggregation Pipeline
Key points:
1.Aggregation Framework
2.sort() and limit()
3.Introduction to Indexes
4.Introduction to Data Modeling
5.Upinsert -- Update or Insert?
1.Aggregation Framework
aggregate
查找listingsAndReviews表中,amentities中含有wifi数据,只显示价格和地址信息。
db.listingsAndReviews.aggregate([
{ "$match": { "amenities": "Wifi" } },
{ "$project": { "price": 1, "address": 1, "_id": 0 }}]).pretty()
等同于:
db.listingsAndReviews.find({ "amenities": "Wifi" }, { "price": 1, "address": 1, "_id": 0 }).pretty()
$group 分组统计
语法如下:
{$group:{
_id:<expression>,// group by Expression
<field1>:{<accumulator1>:<expression1>},
...}}
例:
按照address中的country统计数据的个数,只显示address。
db.listingsAndReviews.aggregate([
{ "$project": { "address": 1, "_id": 0 }},
{ "$group": { "_id": "$address.country", "count": { "$sum": 1 } } } ])
2.sort() and limit()
sort()将数据进行排序,
1 是正序A-Z
-1 是逆序 Z-A
limit()用来指定显示的数据行数,。
limit(1)只显示一行结果
例:zips表中针对pop列进行倒序排列,并只显示10行
db.zips.find().sort({ "pop": -1 }).limit(10)
limit().sort()与 sort().limit()结果相同。
3.Introduction to Indexes
用来使查询更为快速,避免使用sort
例:给trips表中的birth year按照正序添加索引
db.trips.createIndex({"birth year":1})
1 代表正序A-Z
-1 代表逆序Z-A
可以同时添加多个索引。
4.Introduction to Data Modeling
更多资料参考:https://docs.mongodb.com/manual/core/data-modeling-introduction/
5.Upinsert -- Update or Insert?
update:
db.collection.updateOne({<query to locate>},{<update>})
Upinsert is a hybrid of update and inserts,it should only be used when it is needed.
如果upsert为 true,则如果需要更新的数据存在是则更新,若更新的数不存在的时候,插入一条新数据。
db.collection.updateOne({<query>},{<update>},{"upsert":true})