Docs Menu
Docs Home
/
MongoDB マニュアル
/ / /

$and(集計)

項目一覧

  • 定義
  • 動作
  • Error Handling
$and

1 つまたは複数の式を評価し、すべての 式がtrueの場合、または引数式なしで実行した場合はtrueを返します。 それ以外の場合、 $andfalseを返します。

$and 構文:

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

式の詳細については、「 式 」を参照してください。

falseブール値に加えて、 $andは、次のnull0undefined値をfalseとして評価します。 $andは、ゼロ以外の数値と配列を含む他のすべての値をtrueとして評価します。

結果
{ $and: [ 1, "green" ] }
true
{ $and: [ ] }
true
{ $and: [ [ null ], [ false ], [ 0 ] ] }
true
{ $and: [ null, true ] }
false
{ $and: [ 0, true ] }
false

クエリ エンジンでクエリが最適化されるよう、$and はエラーを次のように処理します。

  • $and に指定した式が単独で評価されるとエラーが発生する場合、その式を含む $and でエラーが発生することがありますが、必ずしもエラーが発生するわけではありません。

  • $and に最初に指定した式の後に式を指定すると、最初の式が false と評価されていてもエラーが発生することがあります。

たとえば、次のクエリでは、 $x0 の場合、常にエラーが発生します。

db.example.find( {
$expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] }
} )

$and に複数の式を指定した次のクエリでは、$x0 であるドキュメントがある場合にエラーが発生することがあります

db.example.find( {
$and: [
{ x: { $ne: 0 } },
{ $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
]
} )

次のドキュメントを使用してサンプルのinventoryコレクションを作成します。

db.inventory.insertMany([
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },
{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },
{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },
{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },
{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])

この操作では、$and 演算子を使用して、qty が 100 より大きく、かつ 250 より小さいかどうかを判断します。

db.inventory.aggregate(
[
{
$project:
{
item: 1,
qty: 1,
result: { $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] } ] }
}
}
]
)

この操作は、次の結果を返します。

{ "_id" : 1, "item" : "abc1", "qty" : 300, "result" : false }
{ "_id" : 2, "item" : "abc2", "qty" : 200, "result" : true }
{ "_id" : 3, "item" : "xyz1", "qty" : 250, "result" : false }
{ "_id" : 4, "item" : "VWZ1", "qty" : 300, "result" : false }
{ "_id" : 5, "item" : "VWZ2", "qty" : 180, "result" : true }

戻る

$allElementsTrue