MongoDBでは、$and 集計パイプライン演算子は1つ以上の式を評価し、trueを返します それらがすべてtrueと評価された場合 、または引数なしで呼び出された場合。それ以外の場合は、falseを返します 。
構文
構文は次のようになります:
{ $and: [ <expression1>, <expression2>, ... ] } 例
dataというコレクションがあるとします。 次のドキュメントで:
{ "_id" : 1, "a" : 10, "b" : 2, "c" : 20 }
$andを使用すると次のようになります そのドキュメントに対して2つの条件をテストするには:
db.data.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $and: [
{ $gt: [ "$a", 9 ] },
{ $lt: [ "$b", 3 ] }
] }
}
}
]
) 結果:
{ "a" : 10, "b" : 2, "result" : true }
$and 返されたtrue 。
3つ以上の引数
前述のように、$and 1つ以上の式を受け入れます。前の例では、2つの式を使用しています。 3つを使用する例を次に示します。
db.data.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
a: 1,
b: 1,
c: 1,
result: { $and: [
{ $gt: [ "$a", 9 ] },
{ $lt: [ "$b", 3 ] },
{ $gt: [ "$c", 30 ] }
] }
}
}
]
) 結果:
{ "a" : 10, "b" : 2, "c" : 20, "result" : false }
この場合、結果はfalseになります 、3番目の式はfalseと評価されるため 。 1つの式がfalseと評価された場合 、結果はfalseになります ($and すべての式がtrueである必要があります trueを返す前に 。
1つの引数
その$andを考えると 1つ以上の式を受け入れ、単一の引数を指定することが可能です。
例:
db.data.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
a: 1,
result: { $and: [ { $gt: [ "$a", 9 ] } ] } }
}
]
) 結果:
{ "a" : 10, "result" : true } ゼロ、ヌル、および未定義の値
$and オペレーターは0を評価します 、null 、およびundefined falseとして 。
次のドキュメントがあるとします。
{ "_id" : 2, "a" : 0, "b" : 2 }
{ "_id" : 3, "a" : 10, "b" : 0 }
{ "_id" : 4, "a" : 0, "b" : 0 }
{ "_id" : 5, "a" : null, "b" : 2 }
{ "_id" : 6, "a" : 10, "b" : null }
{ "_id" : 7, "a" : null, "b" : null }
{ "_id" : 8, "a" : undefined, "b" : 2 }
{ "_id" : 9, "a" : 10, "b" : undefined }
{ "_id" : 10, "a" : undefined, "b" : undefined }
$andを適用すると次のようになります :
db.data.aggregate(
[
{ $match: { _id: { $in: [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } } },
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $and: [ "$a", "$b" ] } }
}
]
) 結果:
{ "a" : 0, "b" : 2, "result" : false }
{ "a" : 10, "b" : 0, "result" : false }
{ "a" : 0, "b" : 0, "result" : false }
{ "a" : null, "b" : 2, "result" : false }
{ "a" : 10, "b" : null, "result" : false }
{ "a" : null, "b" : null, "result" : false }
{ "a" : undefined, "b" : 2, "result" : false }
{ "a" : 10, "b" : undefined, "result" : false }
{ "a" : undefined, "b" : undefined, "result" : false }
ここでは、単にフィールドを式として使用しました。予想どおり、それらはすべてfalseを返しました 。
引数を1つだけ適用すると、次のようになります。
db.data.aggregate(
[
{ $match: { _id: { $in: [ 2, 3, 5, 8 ] } } },
{ $project: {
_id: 0,
a: 1,
result: { $and: [ "$a" ] } }
}
]
) 結果:
{ "a" : 0, "result" : false }
{ "a" : 10, "result" : true }
{ "a" : null, "result" : false }
{ "a" : undefined, "result" : false }
trueを返します 値が10の場合 しかしfalse 他のすべての場合。
$andを呼び出します 引数なし
引数なしで呼び出された場合、$and 演算子はtrueと評価されます 。
例:
db.data.aggregate(
[
{ $match: { _id: { $in: [ 1 ] } } },
{ $project: {
_id: 0,
result: { $and: [ ] } }
}
]
) 結果:
{ "result" : true }