Docs Menu
Docs Home
/
MongoDB Manual
/ / /

$bitAnd (aggregation)

On this page

  • Definition
  • Syntax
  • Behavior
  • Examples
  • Learn More

New in version 6.3.

$bitAnd

Returns the result of a bitwise and operation on an array of int or long values.

The $bitAnd operator has the following syntax:

{ $bitAnd: { [ <expression1>, <expression2>, ... ] }

If the operands include both integers and long values, MongoDB sign-extends the calculated integer result and returns a long value. Otherwise, if the operands include only integers or only longs, MongoDB returns results with the corresponding value type.

Note

All numbers in mongosh are doubles, not integers. To to specify integers in mongosh, use the NumberInt() or the NumberLong() constructor. To learn more, see Int32 or Long.

To learn how your MongoDB driver handles numeric values, refer to your driver's documentation.

If any arguments in the array are of a different data type such as a string, double, or decimal, MongoDB returns an error.

If the argument is an empty array, the operation returns NumberInt(-1).

If any of the operands equate to null, the operation returns null.

The examples on this page use the switches collection, which contains the following documents:

db.switches.insertMany( [
{ _id: 0, a: NumberInt(0), b: NumberInt(127) },
{ _id: 1, a: NumberInt(2), b: NumberInt(3) },
{ _id: 2, a: NumberInt(3), b: NumberInt(5) }
] )

The following aggregation uses the $bitAnd operator in the $project stage:

db.switches.aggregate( [
{
$project: {
result: {
$bitAnd: [ "$a", "$b" ]
}
}
}
])

The operation returns the following results:

[
{ _id: 0, result: 0 }
{ _id: 1, result: 2 }
{ _id: 2, result: 1 }
]

The following aggregation uses the $bitAnd operator in the $project stage:

db.switches.aggregate( [
{
$project: {
result: {
$bitAnd: [ "$a", NumberLong("63") ]
}
}
}
])

The operation returns the following results:

[
{ _id: 0, result: NumberLong("0") }
{ _id: 1, result: NumberLong("2") }
{ _id: 2, result: NumberLong("3") }
]
  • Aggregation Operators

  • $bit

Back

$binarySize (aggregation)