In mongo db, I have the input collection
- 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.
CodePudding user response:
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"
}
}
}
}
])