简体   繁体   中英

Create a flat materialized view from a mongo collection

In mongo db, I have the input collection

  1. Collection name - dirPermission and sample record
[
  {
    dirId: "1",
    dirName: "firstDir",
    usersRead: [
      "user1",
      "user2"
    ],
    userWrite: [
      "user2",
      "user3"
    ]
  }
]

and I want to create a materialized view like the below

    [{
     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'
    }]

Again since my back ground is more of SQL + Java, I am struggling to find an answer using mongodb and any pointers will be helpful.

You can use $setUnion to create a distinct set of users. $unwind it to create documents and use $cond to set canRead and canWrite .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM