2

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.

1 Answer 1

3

Since you do not know what are the fields in your documents, You have to convert them to k-v pair using $objectToArray then use $filter to filter out the fields which are not in $allowed array. FInally use $arrayToObject to get initial shape.

db.collection.aggregate([
  { $replaceRoot: {
    newRoot: {
      $arrayToObject: {
        $filter: {
          input: { $objectToArray: "$$ROOT" },
          cond: { $in: ["$$this.k", "$allowed"] }
        }
      }
    }
  }}
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the quick response. It's working. I have learned something new today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.