arrays - MongoDB:如何计算键中值的数量

标签 arrays json mongodb

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

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

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

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

谢谢!

最佳答案

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

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

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

The $size operator matches any array with the number of elements specified by the argument. For example:

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

关于arrays - MongoDB:如何计算键中值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66883584/

相关文章:

具有条件总和的 MongoDB 聚合

javascript - 如何使用钩子(Hook)迭代数组并保存数据

javascript - 将数组传递给另一个函数

javascript - 如何将多个零插入已存在的数组

c - 为什么 p 不显示与 a 相同的地址?

java-如何检查发送的响应类型(响应为 JSON 格式)

android - 设置异步任务以将 Json 加载到 ListView 中

python - 由于转义字符,python 中的 Json 打印输出与写入输出不同

mongodb - mongodb 的问题

MongoDB/Mongoose 按日期排序和按用户分组