MongoDB で NOT と AND を併用する 質問する

MongoDB で NOT と AND を併用する 質問する

$andMongoDB で句を否定しようとしていますが、MongoError: invalid operator: $andメッセージが返されます。基本的に、私が達成したいのは次のことです。

query = { $not: { $and: [{institution_type:'A'}, {type:'C'}] } }

これをmongoクエリで表現することは可能ですか?

サンプルコレクションは次のとおりです。

{ "institution_type" : "A", "type" : "C" }
{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }

取り戻したいものは以下のとおりです。

{ "institution_type" : "A", "type" : "D" }
{ "institution_type" : "B", "type" : "C" }
{ "institution_type" : "B", "type" : "D" }

ベストアンサー1

あなたが探しているのは でNOT (A AND C)、これは と同等ですNOT A OR NOT C:

db.collection.find({
  "$or": [
    {"institution_type": {"$ne": "A"}},
    {"type": {"$ne": "C"}}
  ]
})

MongoDBには$nor論理演算子は、「1 つ以上のクエリ式の配列に対して論理 NOR 演算を実行し、配列内のすべてのクエリ式に失敗したドキュメントを選択します」。したがって、同等のクエリは次のようになります。

db.collection.find({
  "$nor": [
    {"institution_type": "A"},
    {"type": "C"}
  ]
})

受け入れられた回答では$where演算子の使用を推奨していますが、ここでは不要であり、パフォーマンスに負担がかかります。

おすすめ記事