【问题标题】:Mongo Db array filter ($filter)Mongodb数组过滤器($filter)
【发布时间】:2021-10-02 17:03:58
【问题描述】:

我有简单的 mongo 集合:

{
  ...
  customerProducts: [
    { organizationId: ObjectId('x') },
    { organizationId: ObjectId('y') },
    { organizationId: ObjectId('z') },
  ]
  ...
}

我需要过滤数组customerProducts 并使用organizationId = ObjectId('x') 保留元素。 我尝试通过$filter 进行操作。我的做法:

aggregation([{
  $project: {
    'customerProducts': {
      $fiter: {
        input: '$customerProducts',
        as: 'item',
        cond: { $eq: ['$$item.organizationId', ObjectId('x') }
      }
    }
  }
}])

但 Compass 认为 - “Stage 必须是格式正确的文档”。我做错了什么?

【问题讨论】:

  • 1) 操作员名称应该是$filter 而不是$fiter 2) 缺少$eq 的结束] 数组括号=> cond: { $eq: ['$$item.organizationId', ObjectId('x')] }
  • 谢谢,但还是不行。
  • 使用编辑器帮助您自动配对 [] 和 {},这很难手动完成。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您没有用{} 包装$filter 内容。像这样更改您的代码:

db.collection.aggregate([
  {
    "$project": {
      "customerProducts": {
        "$filter": {
          "input": "$customerProducts",
          "cond": {
            "$eq": [
              "$$this.organizationId",
              ObjectId("111111111111111111111111")
            ]
          }
        }
      }
    }
  }
])

Working example

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多