💚 Unary operator:
A unary operator is an operator that performs the operation on a single field or value within a document during the aggregation pipeline. It performs its operation only in a single field not performs its operator for the entire group.
** Unary operators are usually used in the $project stage.
** In the group stage, the unary operator can be used only in conjunction with the accumulator.
$type
: Returns the BSON data type of a field. For example, you can use $type
it to filter documents based on the data type of a specific field.
$size
: Returns the number of elements in an array field. This can be useful when working with arrays to perform operations based on the array size.
$exists
: Checks if a field exists in a document. This is useful for filtering documents that contain or do not contain a specific field.
$not
: Negates the boolean value of a given expression. It's used to perform logical negation on a condition.
$type:
db.persons.aggregate([
{$project: {name: 1,
nameType: {$type: "$name"},
ageType: {$type: "$age"},
tagsType: {$type: "$tags"},
companyType: {$type: "$company"}}}
])
Output:
{
"_id" : ObjectId("64dca7221921e7b46b5ad811"),
"name" : "Aurelia Gonzales",
"nameType" : "string",
"ageType" : "int",
"tagsType" : "array",
"companyType" : "object"
}
Post a Comment