【问题标题】:Aggregation pipeline for filtering the array用于过滤数组的聚合管道
【发布时间】:2020-08-13 12:26:34
【问题描述】:

我有一个像这样的数组:

const tags = ["a", "b", "c"];

我的收藏看起来像:

[{
  _id: asdsadasd,
  tagName: "a"
 },
 {
  _id: qweqewqe,
  tagName: "d"
 }
]

我想过滤 tags 数组,使其不包含集合中的任何标签(tagName 字段)。

样本输出:

["b", "c"]

这是我尝试过的:

[
  {
    '$group': {
      '_id': null, 
      'tags': {
        '$push': '$tagName'
      }
    }
  }, {
    '$project': {
      'filteredTags': {
        '$filter': {
          'input': tags, 
          'as': 'item', 
          'cond': {
            '$not': {
              '$in': [
                '$$item', '$tags'
              ]
            }
          }
        }
      }
    }
  }
]

这工作正常,但我想知道是否有更有效的方法可以使用聚合管道或任何方式来做到这一点。

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    db.collection.aggregate([
      { "$group": {
        "_id": null,
        "data": { "$push": "$tagName" }
      }},
      { "$project": {
        "tags": {
          "$setDifference": [
            ["a", "b", "c"],
            "$data"
          ]
        }
      }}
    ])
    

    MongoPlayground

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 2020-09-23
      • 2021-02-09
      • 2021-02-03
      • 2015-05-08
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多