MongoDB query to find "where" Billing Address is Equal to Delivery Address from documents?

To find documents where billing address equals delivery address in MongoDB, use the $where operator with JavaScript expressions to compare field values within the same document.

Syntax

db.collection.find({
    $where: "this.field1 == this.field2"
});

Sample Data

db.demo589.insertMany([
    {deliveryAddress: "US", billingAddress: "UK"},
    {deliveryAddress: "US", billingAddress: "US"},
    {deliveryAddress: "US", billingAddress: "AUS"},
    {deliveryAddress: "UK", billingAddress: "US"}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5e92c117fd2d90c177b5bccc"),
        ObjectId("5e92c11bfd2d90c177b5bccd"),
        ObjectId("5e92c11ffd2d90c177b5bcce"),
        ObjectId("5e92c127fd2d90c177b5bccf")
    ]
}

Display all documents from the collection ?

db.demo589.find();
{ "_id" : ObjectId("5e92c117fd2d90c177b5bccc"), "deliveryAddress" : "US", "billingAddress" : "UK" }
{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }
{ "_id" : ObjectId("5e92c11ffd2d90c177b5bcce"), "deliveryAddress" : "US", "billingAddress" : "AUS" }
{ "_id" : ObjectId("5e92c127fd2d90c177b5bccf"), "deliveryAddress" : "UK", "billingAddress" : "US" }

Example: Find Equal Addresses

Query to find documents where billing address equals delivery address ?

db.demo589.find({
    $where: "this.deliveryAddress == this.billingAddress"
});
{ "_id" : ObjectId("5e92c11bfd2d90c177b5bccd"), "deliveryAddress" : "US", "billingAddress" : "US" }

Key Points

  • The $where operator allows JavaScript expressions for complex field comparisons.
  • Use this keyword to reference fields in the current document.
  • $where queries are slower than standard operators as they execute JavaScript.

Conclusion

The $where operator enables field-to-field comparison within documents using JavaScript expressions. While powerful, use it sparingly as it's less performant than native MongoDB operators.

Updated on: 2026-03-15T03:46:05+05:30

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements