【问题标题】:return complete document with array containing satisfying condition in mongodb在 mongodb 中返回包含满足条件的数组的完整文档
【发布时间】:2020-07-16 07:27:42
【问题描述】:

我真的陷入了这个问题,使用聚合和投影尝试了一切,但还没有运气,请帮我找出一些最佳方法,

这就是我的文档的样子

  {
  engagement: {
    loves: [ 5e87a316457e874ce886356c,5e87a316457e874ce886356d, 5e87a316457e874ce886356e, 5e87a316457e874ce886356f],
    loveCount: 4,
  },
  _id: 5e87c097c9374e6628a499b
}

现在我想提供一个loves数组的元素,并在此基础上产生以下结果

元素:5e87a316457e874ce886356d

结果

  {
  engagement: {
    loves: [ 5e87a316457e874ce886356d],
    loveCount: 4,
  },
  _id: 5e87c097c9374e6628a499b
}

元素:XYZABC

结果

  {
  engagement: {
    loves: [],
    loveCount: 4,
  },
  _id: 5e87c097c9374e6628a499b
}

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你需要$filter:

    db.collection.aggregate([
        {
            $addFields: {
                "engagement.loves": {
                    $filter: {
                        input: "$engagement.loves",
                        cond: {
                            $eq: [ "$$this", "5e87a316457e874ce886356d" ]
                        }
                    }
                }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

    • 哦,非常感谢,但我怎样才能在这个 senerio 中添加多个要过滤的数组,就像一个过滤器用于爱一个过滤器,用于具有相同逻辑的最爱
    • @Sundeep 这不是问题 - 您可以添加更多语句,例如 engagement.favorites 等。
    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多