hengo
V2EX  ›  问与答

请教大家一个关于 MongoDB 聚合查询的问题

  •  
  •   hengo · Aug 23, 2019 · 2246 views
    This topic created in 2646 days ago, the information mentioned may be changed or developed.

    能不能在多条MongoDB记录中,聚合查询,一次输出多个字段的总记录条数 比如

    { "month" : 3, "day" : 5, "year" : 2019 }
    { "month" : 2, "day" : 4, "year" : 2018 }
    { "month" : 3, "day" : 1, "year" : 2018 }
    { "month" : 5, "day" : 2, "year" : 2019 }
    { "month" : 5, "day" : 1, "year" : 2019 }
    

    比如一次性查询: { month = 3, year = 2019 }

    输出结果集: { monthCount = 2, yearCount = 3}

    现在我只能根据字段去查找记录数,不能去给字段匹配相应的值去查询。

    7 replies  •  2019-09-06 09:27:15 +08:00
    lwd219
    lwd219
    Aug 23, 2019
    1
    aggregate ?
    licht114
    licht114
    Aug 23, 2019
    2
    坐等 MongoDB 大神,我也想知道有没有骚操作
    hengo
    hengo
    OP
    Aug 23, 2019 via Android
    3
    @lwd219 对,以前我是一个一个查的,效率比较低,因为我们这边数据量可能比较大,所以想一次性查,效率稍微高一点。
    Philippa
    Philippa
    Aug 23, 2019
    4
    ```
    {
    "$group": {
    "_id": null,
    "month": {
    '$sum': {
    '$cond': [
    {'$eq': ["$month", "3"]},
    1, 0
    ]
    }
    },
    "year": {
    '$sum': {
    '$cond': [
    {'$eq': ["$year", "2019"]},
    1, 0
    ]
    }
    },
    }
    },
    {$project: { 'year': 1, 'month': 1, _id: 0 } }
    ```
    没测过
    phpdever
    phpdever
    Aug 23, 2019❤️1
    5
    phpdever
    phpdever
    Aug 23, 2019❤️1
    6
    @licht114 看我回复
    licht114
    licht114
    Sep 6, 2019
    7
    @phpdever 感谢大神分享
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3096 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 10:12 · PVG 18:12 · LAX 02:12 · JFK 05:12
    ♥ Do have faith in what you're doing.