【问题标题】:MongoDB: How to count number of values in keyMongoDB:如何计算键中值的数量
【发布时间】:2021-03-31 07:38:26
【问题描述】:

我是 MongoDB 的新手,我需要帮助弄清楚如何对 MongoDB 中的键执行聚合并使用该结果返回匹配项。

例如,如果我有一个名为 Fruits 的集合,其中包含以下文档:

{
    "id": 1,
    "name": "apple",
    "type": [
      "Granny smith",
      "Fuji"
    ]
  }, {
    "id": 2,
    "name": "grape",
    "type": [
      "green",
      "black"
    ]
  }, {
    "id": 3,
    "name": "orange",
    "type": [
      "navel"
    ]
  }

我如何编写一个查询来返回两种水果的名称,即苹果和葡萄?

谢谢!

【问题讨论】:

    标签: arrays json mongodb


    【解决方案1】:

    演示 - https://mongoplayground.net/p/ke3VJIErhvb

    使用$size获取2个类型的记录

    https://docs.mongodb.com/manual/reference/method/db.collection.find/#mongodb-method-db.collection.find

    $size 运算符匹配任何具有参数指定元素数量的数组。例如:

    db.collection.find({
      type: { "$size": 2 } // match document with type having size 2
    },
      { name: 1 } // projection to get name and _id only  
    )
    

    【讨论】:

      【解决方案2】:

      要获取数组的长度,您应该在$project 管道阶段使用$size 运算符

      所以管道 $project 阶段应该是这样的

      {
        "$project": {
          "name": "$name",
          type: {
            "$size": "$type"
          }
        }
      }
      

      这是一个相同的工作示例⇒https://mongoplayground.net/p/BmS9BGhqsFg

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-17
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 2018-03-11
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        相关资源
        最近更新 更多