MongoDB University笔记总结-M001_Chapter 5: Indexing and Aggregation Pipeline

本文介绍了MongoDB的基础课程,包括Aggregation Framework的使用、sort()和limit()操作,以及索引的重要性。通过实例讲解了如何创建索引提升查询速度,以及数据模型设计的基本原则。此外,还讨论了upsert操作和何时选择使用它。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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})

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值