V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
a19950321
V2EX  ›  问与答

mongo 聚合查询

  •  
  •   a19950321 · 2019-04-12 11:32:16 +08:00 · 1080 次点击
    这是一个创建于 1831 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想查 id:1 type:1 的所有用户一共是多少条 ,只要 sum ,应该怎么写啊大神们

    3 条回复    2019-04-12 14:07:31 +08:00
    a19950321
        1
    a19950321  
    OP
       2019-04-12 11:35:44 +08:00
    大神救救急
    Trim21
        2
    Trim21  
       2019-04-12 13:55:08 +08:00 via Android
    count

    具体怎么用看文档
    Vegetable
        3
    Vegetable  
       2019-04-12 14:07:31 +08:00
    普通查询 count({id:1,sum:1})


    聚合里边,能 match 就 match,
    ```javascript
    db.getCollection("example").aggregate([
    {
    $match: {
    id: 1,
    type: 1
    }
    },
    {
    $group: {
    _id: 1,
    count:{$sum:1}
    }
    }])
    ```
    如果不能 match,就要配合$cond
    ```javascript
    db.getCollection("example").aggregate([
    {
    $group: {
    _id: 1,
    count: {
    $sum: {
    $cond: {
    if: {
    $and: [
    {
    $eq: ["$type", 1]
    },
    {
    $eq: ["$id", 1]
    }
    ]
    },
    then: 1,
    else: 0
    }
    }
    }
    }
    }
    ])
    ```
    我可讨厌死 mogodb 的聚合了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1288 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:44 · PVG 01:44 · LAX 10:44 · JFK 13:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.