Mongodb通过使用输入数组进行聚合

时间:2020-09-13 08:05:46

标签: javascript database mongodb mongoose nosql

我正在努力为MongoDB数据库创建汇总查询。

这是我的输入数组

recipients = [1,2,7]

这是我的数据库集合

{
    "chapter": 1,
    "targets": [
      {
        type: 'user',
        recipient: 1
      }
    ]
  },
  {
    "chapter": 1,
    "targets": [
      {
        type: 'user',
        recipient: 2
      }
    ]
  },
  {
    "chapter": 2,
    "targets": [
      {
        type: 'user',
        recipient: 3
      }
    ]
  },
  {
    "chapter": 3,
    "targets": [
      {
        type: 'user',
        recipient: 4
      }
    ]
  },

所需的输出

should be [] because 7 doesn't exist in targets.recipient in the collection

这是我到目前为止尝试过的

db.collection.aggregate([
  {
      $match: {
        'targets.recipient': { $in: recipients },
      },
    }
])

任何建议,谢谢。

2 个答案:

答案 0 :(得分:2)

$in的工作方式是:如果文档的值与作为参数传递的数组之间存在匹配,则它将返回文档。看起来您可以使用const mapDispatchToProps = { fetchBlog } 进行初始过滤,但是仅当结果集包含输入数组中的所有值时,才想返回结果。为了实现它,您可以使用$group获得所有匹配的结果,然后应用$all

$in

Mongo Playground

答案 1 :(得分:0)

1