猫鼬过滤器子文档

时间:2019-02-19 21:31:43

标签: mongodb mongoose nosql aggregation-framework

具有类似以下的模式

     {
  "_id": ObjectId("..."),
  "views": [
    {
      "name": "AAA",
      "permissions": ['PERM_1','PERM_2']
    },
    {
      "name": "BBB",
      "permissions": ['PERM_2']
    },
    {
      "name": "CCC",
      "permissions": ['PERM_3']
    }]
}

我想这样获得包含“ PERM_1”和“ PERM_3”的视图的结果:

{
 "_id": ObjectId("..."),
 "views": [
        {
  "name": "AAA",
  "permissions": ['PERM_1','PERM_2']
 },
 {
   "name": "CCC",
   "permissions": ['PERM_3']
 }]
}

但是,我并没有真正获得想要的结果。这是我的查询:

Schema.aggregate([
{
    $project: {
        views: {
            $filter: {
                input: '$views.permissions',
                as: 'perm',
                cond: {
                    ????? // return only PERM_1 and PERM_3
                }
            }
        }
    }
}])

谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

条件的内容可以是:

$filter: {
  input: '$views',
  as: 'perm',
  cond: {
    { $in: [ "$$perm.permissions", ['PERM_1','PERM_2']] }
  }
}

您可以查看mongo技术文档以了解更多详细信息