MongoDB query with fields in the same document?


You can use $where operator for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"John"},"NewStudentDetails":{"StudentName":"Carol"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90096ed3c9d04998abf017")
}
> db.queryInSameDocumentsDemo.insertOne({"StudentDetails":{"StudentName":"Bob"},"NewStudentDetails":{"StudentName":"Bob"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900a435705caea966c5573")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c90096ed3c9d04998abf017"),
   "StudentDetails" : {
      "StudentName" : "John"
   },
   "NewStudentDetails" : {
      "StudentName" : "Carol"
   }
}
{
   "_id" : ObjectId("5c900a435705caea966c5573"),
   "StudentDetails" : {
      "StudentName" : "Bob"
   },
   "NewStudentDetails" : {
      "StudentName" : "Bob"
   }
}

Case 1 − Here is the query with fields in the same document. We have used the equality (==) operator here. The query is as follows −

> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName == this.NewStudentDetails.StudentName" } ).pretty();

The following is the output −

{
   "_id" : ObjectId("5c900a435705caea966c5573"),
   "StudentDetails" : {
      "StudentName" : "Bob"
   },
   "NewStudentDetails" : {
      "StudentName" : "Bob"
   }
}

Case 2 − Here is the query with fields in the same document. We have used not equal to operator.

The query is as follows −

> db.queryInSameDocumentsDemo.find( { $where: "this.StudentDetails.StudentName != this.NewStudentDetails.StudentName" } ).pretty();

The following is the output −

{
   "_id" : ObjectId("5c90096ed3c9d04998abf017"),
   "StudentDetails" : {
      "StudentName" : "John"
   },
   "NewStudentDetails" : {
      "StudentName" : "Carol"
   }
}

Updated on: 30-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements