mongodb 从mongo集合创建平面物化视图

wfsdck30  于 2023-01-30  发布在  Go
关注(0)|答案(1)|浏览(140)

在mongo db中,我有输入集合
1.采集名称-dirPermission和样品记录

[
  {
    dirId: "1",
    dirName: "firstDir",
    usersRead: [
      "user1",
      "user2"
    ],
    userWrite: [
      "user2",
      "user3"
    ]
  }
]

我想创建如下所示的示例化视图

[{
     dirId:'1',
     dirName:'firstDir',
     userId:'user1',
     canRead:'Y',
     canWrite:'N'
    },
    {
     dirId:'1',
     dirName:'firstDir',
     userId:'user2',
     canRead:'Y',
     canWrite:'Y'
    },
    {
     dirId:'1',
     dirName:'firstDir',
     userId:'user3',
     canRead:'N',
     canWrite:'Y'
    }]

同样,由于我的背景更多的是SQL + Java,我很难使用mongodb找到答案,任何指针都会很有帮助。

ovfsdjhp

ovfsdjhp1#

您可以使用$setUnion创建一组不同的用户。$unwind用于创建文档,使用$cond设置canReadcanWrite

db.collection.aggregate([
  {
    "$addFields": {
      "allUsers": {
        $setUnion: [
          "$usersRead",
          "$userWrite"
        ]
      }
    }
  },
  {
    "$unwind": "$allUsers"
  },
  {
    "$project": {
      dirId: 1,
      dirName: 1,
      userId: "$allUsers",
      canRead: {
        "$cond": {
          "if": {
            "$in": [
              "$allUsers",
              "$usersRead"
            ]
          },
          "then": "Y",
          "else": "N"
        }
      },
      canWrite: {
        "$cond": {
          "if": {
            "$in": [
              "$allUsers",
              "$userWrite"
            ]
          },
          "then": "Y",
          "else": "N"
        }
      }
    }
  }
])

Mongo Playground

相关问题