【问题标题】:Count number of fields that match in an Array of Object in mongodb计算 mongodb 中对象数组中匹配的字段数
【发布时间】:2021-06-14 15:20:43
【问题描述】:

我有什么

我在MongoDB 有一个这样的数据库:

{
    "_id": {
        "$oid": "60ba531acbfed3545c51a49e"
    },
    "email": "shaswat.dharaiya@gmail.com",
    "Formats": [{
        "format": "AST-QC",
    }],
    "Series": [{
        "seq": "AST-QC - 1",
     },
     {
        "seq": "AST-QC - 2",
     },
     {
        "seq": "AST-QD - 1",
     }]
}

我使用此查询成功地从 Formats 数组中获取数据:

const pipeline =  [
    { $match: { "email": email } },
    { $unwind: "$Formats" },    
]
const res = await colc.aggregate(pipeline)

我想要什么

连同Formats 数组中的数据,我需要seqSeries 数组中使用的每个format 的计数。

我确定可以使用$addFields 来完成,类似这样。

const pipeline =  [
    { $match: { "email": email } },
    { $unwind: "$Formats" },
    { $addFields: {"Formats.count": 0} }
]
const res = await colc.aggregate(pipeline)

但我不确定如何。

我不想使用 .count() 调用另一个查询

【问题讨论】:

  • 您需要多少计数? AST-QC - 1 连接数字或匹配字符串?
  • 只是格式中的匹配字符串,即AST-QC 不是连接数字。

标签: javascript node.js mongodb aggregation-framework


【解决方案1】:
  • $filter 迭代 Series 数组的循环
  • $regexMatchseb 搜索格式
  • $size 获取过滤结果中的总元素
const pipeline = [
  { $match: { email: email } },
  { $unwind: "$Formats" },
  {
    $addFields: {
      "Formats.count": {
        $size: {
          $filter: {
            input: "$Series",
            cond: {
              $regexMatch: {
                input: "$$this.seq",
                regex: "$Formats.format"
              }
            }
          }
        }
      }
    }
  }
]

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2023-01-23
    相关资源
    最近更新 更多