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"
}
You can use $type to check the type of field,
$reduce
input $$ROOT
object as array using $objectToArray
string
then concat with initialValue and return$arrayToObject
$replaceWith
will replace root to new returned objectdb.collection.aggregate([
{
$replaceWith: {
$arrayToObject: {
$reduce: {
input: { $objectToArray: "$$ROOT" },
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$cond: [
{ $eq: [{ $type: "$$this.v" }, "string"] },
["$$this"],
[]
]
}
]
}
}
}
}
}
])