I have my collection of structure
{
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
allowed: ['a', 'b']
}
In this collection, allowed array stores fields name to be fetched. It is set by the user preference which he wants to fetch and can change those selected fields and is updated in allowed array.
I want to fetch using MongoDB aggregate and project in some way that allowed array will be used without manually listing all the fields in $project
{ $project: { a: 1, b: 1 } }
I have one solution like using below project in aggregate
db.getCollection("dummy").aggregate([
{ $match: {} },
{
$project: {
a: {
$cond: {
if: { $in: ["a", "$allowed"] },
then: "$a",
else: "$$REMOVE",
},
},
b: {
$cond: {
if: { $in: ["b", "$allowed"] },
then: "$b",
else: "$$REMOVE",
},
},
},
},
]);
but this also requires listing all fields. I am looking for an alternate solution that projects fields in the allowed array without listing all fields manually in $project.