MongoDB: Project only fields of a specific type

Viewed 284

Is there a way in MongoDB to project all fields of a document that have a specific type?

For example if I have the following document:

{
  _id: 5dde4c55c6c36b3bb4f5ad30,
  name: "Peter",
  age: 45,
  division: "marketing"
}

I would like to say: Return only the fields of type string. This way I would end up with:

{
  _id: 5dde4c55c6c36b3bb4f5ad30,
  name: "Peter",
  division: "marketing"
}
1 Answers

You can use $type to check the type of field,

  • $reduce input $$ROOT object as array using $objectToArray
  • check condition if field value type is string then concat with initialValue and return
  • return value will be array we need to convert it to array using $arrayToObject
  • $replaceWith will replace root to new returned object
db.collection.aggregate([
  {
    $replaceWith: {
      $arrayToObject: {
        $reduce: {
          input: { $objectToArray: "$$ROOT" },
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              {
                $cond: [
                  { $eq: [{ $type: "$$this.v" }, "string"] },
                  ["$$this"],
                  []
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Playground

Related