How to query a key having space in its name with MongoDB?

To query a key having space in its name in MongoDB, wrap the field name with spaces in quotes and use dot notation for nested fields.

Syntax

db.collection.find({"field name with spaces": "value"});
db.collection.find({"parent.field name with spaces": "value"});

Create Sample Data

First, let's create a document with a field that has spaces in its name ?

var myValues = {};
myValues["Details"] = {};
myValues["Details"]["Student Name"] = "John";
myValues["Details"]["StudentAge"] = 26;

db.keyHavingSpaceDemo.insertOne(myValues);
{
    "acknowledged": true,
    "insertedId": ObjectId("5ca27e3b6304881c5ce84ba4")
}

Verify Sample Data

db.keyHavingSpaceDemo.find().pretty();
{
    "_id": ObjectId("5ca27e3b6304881c5ce84ba4"),
    "Details": {
        "Student Name": "John",
        "StudentAge": 26
    }
}

Query Field with Spaces

To query the nested field "Student Name" that contains spaces, use dot notation with quotes ?

db.keyHavingSpaceDemo.find({"Details.Student Name": "John"}).pretty();
{
    "_id": ObjectId("5ca27e3b6304881c5ce84ba4"),
    "Details": {
        "Student Name": "John",
        "StudentAge": 26
    }
}

Key Points

  • Always wrap field names containing spaces in double quotes.
  • Use dot notation for nested fields: "parent.field with spaces".
  • The entire field path must be quoted when any part contains spaces.

Conclusion

MongoDB handles field names with spaces by requiring quotes around the field path. Use dot notation with proper quoting to query nested fields containing spaces effectively.

Updated on: 2026-03-15T00:44:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements