MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

2つのフィールドを比較する際のMongoDBクエリ条件?


2つのフィールドを比較する際の条件を照会するには、次の構文を使用します-

db.yourCollectionName.find( { $where: function() { return this.yourFirstFieldName < this.yourSecondFieldName } } ).pretty();

構文を理解するために、ドキュメントを使用してコレクションを作成しましょう。ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです-

> db.comparingTwoFieldsDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":99,"StudentPhysicsMarks":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac09e6cea1f28b7aa0807")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentMathMarks":79,"StudentPhysicsMarks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0b46cea1f28b7aa0808")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"David","StudentAge":24,"StudentMathMarks":39,"StudentPhysicsMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0c96cea1f28b7aa0809")
}
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":87,"StudentPhysicsMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ac0e06cea1f28b7aa080a")
}

find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです。

> db.comparingTwoFieldsDemo.find().pretty();

以下は出力です-

{
   "_id" : ObjectId("5c8ac09e6cea1f28b7aa0807"),
   "StudentName" : "John",
   "StudentAge" : 21,
   "StudentMathMarks" : 99,
   "StudentPhysicsMarks" : 98
}
{
   "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
   "StudentName" : "Carol",
   "StudentAge" : 22,
   "StudentMathMarks" : 79,
   "StudentPhysicsMarks" : 89
}
{
   "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
   "StudentName" : "David",
   "StudentAge" : 24,
   "StudentMathMarks" : 39,
   "StudentPhysicsMarks" : 45
}
{
   "_id" : ObjectId("5c8ac0e06cea1f28b7aa080a"),
   "StudentName" : "Bob",
   "StudentAge" : 23,
   "StudentMathMarks" : 87,
   "StudentPhysicsMarks" : 78
}

これは、2つのフィールドを比較することを条件とするクエリです-

> db.comparingTwoFieldsDemo.find( { $where: function() { return this.StudentMathMarks < this.StudentPhysicsMarks } } ).pretty();

以下は出力です-

{
   "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
   "StudentName" : "Carol",
   "StudentAge" : 22,
   "StudentMathMarks" : 79,
   "StudentPhysicsMarks" : 89
}
{
   "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
   "StudentName" : "David",
   "StudentAge" : 24,
   "StudentMathMarks" : 39,
   "StudentPhysicsMarks" : 45
}

  1. 複数のフィールドの存在を確認するためのMongoDBクエリ

    複数のフィールドの存在を確認するには、$andとともに$existsを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo475.insertOne({"StudentFirstName":"Chris","StudentAge":23});{    "acknowledged" : true,    "insertedId" : ObjectId("5e80c113b0f3fa88e2279088"

  2. find()の一部のフィールドを除外するMongoDBコレクションクエリ?

    以下の構文のように、含めたくないフィールドを0に設定します。ここでは、フィールド「yourFieldName1」と「yourFieldName2」を0-として設定しました。 db.yourCollectionName.find(yourQuery, {yourFieldName1:0,yourFieldName2:0}); 上記の構文を理解するために、ドキュメントを使用してコレクションを作成しましょう- > db.demo567.insertOne({"Name":"Chris",Age:21});{    "ack