MongoDB 聚合管道使用

LogicEcho
• 阅读 1529

数据准备

[
    {
        "name": {
            "first_name": "qingquan",
            "last_name": "zeng"
        },
        "balance": 100
    },
    {
        "name": {
            "first_name": "fengxia",
            "last_name": "yu"
        },
        "balance": 200
    }
]

插入数据

db.accounts.insert([{"name": {"first_name": "qingquan","last_name": "zeng"},"balance": 100},{"name": {"first_name": "fengxia","last_name": "yu"},"balance": 200}])

数据查询

$project

# aggregate 中的 $project 除了可以实现投影效果,还直接使用了一个不存在的字段 client_name ,相当于 mysql 中的 as 语法
> db.accounts.aggregate([{
... $project:{
... _id:0,
... balance:1,
... client_name:"$name.first_name"
... }
... }]);
{ "balance" : 100, "client_name" : "qingquan" }
{ "balance" : 200, "client_name" : "fengxia" }
# 由于 middle_name 不存在,产生的结果就为 null 了
> db.accounts.aggregate([{
... $project:{
... _id:0,
... balance:1,
... name_arr:["$name.first_name","$name.middle_name","$name.first_name"]
... }
... }]);
{ "balance" : 100, "name_arr" : [ "qingquan", null, "qingquan" ] }
{ "balance" : 200, "name_arr" : [ "fengxia", null, "fengxia" ] }

$match 中使用的文档筛选语法,和读取文档时的筛选语法相同

db.accounts.aggregate([
    {
        $match: {
            "name.first_name": 'fengxia'
        }
    }
])
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de9"), "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200 }

$project$match$skip$limit 相结合

db.accounts.aggregate([
    {
        $match: {
            $or: [
                {
                    "name.first_name": 'fengxia'
                },
                {
                    "name.first_name": 'qingquan'
                },          
            ]
        }
    },
    {
        $project: {
            _id: 0
        }
    },
    {
        $skip: 1
    },
    {
        $limit: 1
    }
])
{ "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200 }

$unwind
对本节的数据进行修改

db.accounts.update({'name.first_name':'qingquan'},{
 $set:{
  "currency":["CNY","USD"]
 }
})

db.accounts.update({'name.first_name':'fengxia'},{
 $set:{
  "currency":"GBP"
 }
})

修改后的数据如下,一个用户的currency是数组,另一个用户的currency是字符串

> db.accounts.find()
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de8"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : [ "CNY", "USD" ] }
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de9"), "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200, "currency" : "GBP" }

使用unwind对数组元素进行平铺,可以将currency为数组的记录,从一条记录拆分为多条记录

db.accounts.aggregate([
    {
        $unwind: {
            path: "$currency"
        }
    }
])
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de8"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : "CNY" }
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de8"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : "USD" }
{ "_id" : ObjectId("5d80fd4471c6b2236fb80de9"), "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200, "currency" : "GBP" }

为了方便排查,还可以在设定一个字段,用于数组展开后标记每个元素在原数组的位置

db.accounts.aggregate([
    {
        $unwind: {
            path: "$currency",
            includeArrayIndex:"origin_index"
        }
    }
])
{ "_id" : ObjectId("5d80c37349f3060f1212a055"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : "CNY", "origin_index" : NumberLong(0) }
{ "_id" : ObjectId("5d80c37349f3060f1212a055"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : "USD", "origin_index" : NumberLong(1) }
{ "_id" : ObjectId("5d80c37349f3060f1212a056"), "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200, "currency" : "GBP", "origin_index" : null }

还有一点需要注意的是,$unwind 在产生结果前,默认会直接过滤掉如下记录:

  • currency字段为空数组
  • currency字段不存在
  • currency字段为null

如果不想过滤的话,可以设定 preserveNullAndEmptyArrays 为 true

db.accounts.aggregate([
    {
        $unwind: {
            path: "$currency",
            includeArrayIndex: "origin_index",
            preserveNullAndEmptyArrays: true
        }
    }
])

$sort

  • 1 从小到大
  • -1 从大到小
db.accounts.aggregate([
    {
        $sort: {
            balance: -1
        }
    }
])
{ "_id" : ObjectId("5d80c37349f3060f1212a056"), "name" : { "first_name" : "fengxia", "last_name" : "yu" }, "balance" : 200, "currency" : "GBP" }
{ "_id" : ObjectId("5d80c37349f3060f1212a055"), "name" : { "first_name" : "qingquan", "last_name" : "zeng" }, "balance" : 100, "currency" : [ "CNY", "USD" ] }
MongoDB 聚合操作重复问题https://jacoobwang.github.io/...
点赞
收藏
评论区
推荐文章
Souleigh ✨ Souleigh ✨
4年前
34 个 JavaScript 代码优化技巧
1. 含有多个条件的if语句我们可以在数组中存储多个值,并且可以使用数组的includes方法。//longhandif (x  'abc' || x  'def' || x  'ghi' || x 'jkl') {    //logic}//shorthandif ('abc', 'def
Wesley13 Wesley13
3年前
Unity XLua 官方案例学习
1\.Helloworld1usingUnityEngine;2usingXLua;34publicclassHelloworld:MonoBehaviour{5//Usethisforinitialization
Stella981 Stella981
3年前
Python操作MongoDB代码示例
1importpymongopipinstallpymongo安装python操作mongodb的模块2myclientpymongo.MongoClient(host'127.0.0.1',port27017)指定主机和端口号创建客户端34dblistmyclient
Wesley13 Wesley13
3年前
Java日期时间API系列34
  通过Java日期时间API系列9Jdk8中java.time包中的新的日期时间API类的Period和Duration的区别(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fxkzhangsanx%2Fp%2F12110137.html)
Stella981 Stella981
3年前
OKHttp源码学习
1.HttpURLConnection1publicclassHttpURLConnectionGetAndPost{2privateStringurlAddress"xxxx";34publicvoiddoGet(Stringmethod,Strings)
Stella981 Stella981
3年前
Dockerfile创建tomcat和jdk,并发布java项目
1.准备好需要的jdk和tomcatkun@ubuntu:~$cdtomcatdocker/kun@ubuntu:~/tomcatdocker$lltotal245232drwxrwxrx4kunkun4096May611:34./drwx4ku
Wesley13 Wesley13
3年前
JAVA的接口
用法:1interfaceA{2publicstaticfinalinti10;34publicvoidrunLoad();5}67publicclassDemoimplementsA{8/
Stella981 Stella981
3年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Wesley13 Wesley13
3年前
thinkphp 基本配置
12returnarray(34//定义数据库连接信息5'DB\_TYPE''mysql',//指定数据库是mysql67'DB\_HOST''localhost',89'DB\_NAME''uchome',//数据库名1011'DB\_USER''root
Stella981 Stella981
3年前
OS X Mavericks 10.9.5 (13F34) bt下载地址
OSXMavericks10.9.5(13F34),源http://bitsnoop.com/osxmavericks109513f34dmgq68447977.html磁力链magnet:?xturn:btih:4c887e73cd37228d8dc0746315501edc289acc51&dnOS%20X%2
Wesley13 Wesley13
3年前
34.TCP取样器
阅读文本大概需要3分钟。1、TCP取样器的作用   TCP取样器作用就是通过TCP/IP协议来连接服务器,然后发送数据和接收数据。2、TCP取样器详解!(https://oscimg.oschina.net/oscnet/32a9b19ba1db00f321d22a0f33bcfb68a0d.png)TCPClien