V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
moodasmood
V2EX  ›  程序员

MongoDB 聚合查询问题?

  •  
  •   moodasmood · 2019-07-05 11:20:27 +08:00 · 1688 次点击
    这是一个创建于 1759 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我有个类似这样的数据结构

    {
    "address":[
    "北京",
    "朝阳区",
    "京旺家园"
    ],
    ....
    }
    

    现在我如果需要统计全北京的总数得怎么查呢?

    db.cityLogs.aggregate([
        { '$unwind': '$address' }
        , {
            $group: { _id: "$address", count: { $sum: 1 } }
        }
    ])
    
    

    我这样查出来是按小区分组的。

    5 条回复    2019-07-05 18:22:18 +08:00
    raysmond
        1
    raysmond  
       2019-07-05 14:25:32 +08:00
    $unwind 可以将数组打平,不过好像是 MongoDB 3.2 以上才有的 feature
    Vegetable
        2
    Vegetable  
       2019-07-05 14:47:37 +08:00
    没明白,你想统计所有北京出现的次数?你的方法是可行的,中间需要插一步 match.
    heanhsu
        3
    heanhsu  
       2019-07-05 17:08:10 +08:00
    不知道是不是这个意思

    db.cityLogs.aggregate([
    {
    $unwind:'$address'
    },
    {
    $group:{
    _id: "$_id",
    city:{
    $first:'$address'
    }
    }
    },
    {
    $group:{
    _id: '$city',
    count:{
    $sum:1
    }
    }
    }
    ])
    heanhsu
        4
    heanhsu  
       2019-07-05 17:09:42 +08:00
    不知道是不是这个意思


    ```

    db.cityLogs.aggregate([
    {
    $unwind:'$address'
    },
    {
    $group:{
    _id: "$_id",
    city:{
    $first:'$address'
    }
    }
    },
    {
    $group:{
    _id: '$city',
    count:{
    $sum:1
    }
    }
    }
    ])

    ```
    moodasmood
        5
    moodasmood  
    OP
       2019-07-05 18:22:18 +08:00
    @Vegetable
    @heanhsu

    多谢,确实加个 match 就行了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3528 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:40 · PVG 12:40 · LAX 21:40 · JFK 00:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.