Docs Menu
Docs Home
/
MongoDB Manual
/ / /

Field Names with Periods

On this page

  • Insert a Field Name with a Period
  • Query a Field that has a Period
  • Update a Field that has a Period
  • Learn More

This section summarizes how to insert, query, and update documents with field names that contain a period.

To insert a document that contains a field name with a period, put the field name in quotes.

The following command inserts a document that contains a field name price.usd:

db.inventory.insertOne(
{
"item" : "sweatshirt",
"price.usd": 45.99,
"quantity": 20
}
)

To query for a field that has a period, use the $getField operator.

The following query returns documents where the price.usd field is greater than 40:

db.inventory.find(
{
$expr:
{
$gt: [ { $getField: "price.usd" }, 40 ]
}
}
)
[
{
_id: ObjectId("66145f9bcb1d4abffd2f1b50"),
item: 'sweatshirt',
'price.usd': 45.99,
quantity: 20
}
]

If you don't use $getField, MongoDB treats the field name with a period as an embedded object. For example, the following query matches documents where a usd field inside of a price field is greater than 40:

db.inventory.find( {
"price.usd": { $gt: 40 }
} )

The preceding query would match this document:

{
"item" : "sweatshirt",
"price": {
"usd": 45.99
},
"quantity": 20
}

To update a field that has a period, use an aggregation pipeline with the $setField operator.

The following operation sets the price.usd field to 29.99:

db.inventory.updateOne(
{ "item": "sweatshirt" },
[
{
$replaceWith: {
$setField: {
field: "price.usd",
input: "$$ROOT",
value: 29.99
}
}
}
]
)

If you don't use $setField, MongoDB treats the field name with a period as an embedded object. For example, the following operation does not update the existing price.usd field, and instead inserts a new field usd, embedded inside of a price field:

db.inventory.updateOne(
{ "item": "sweatshirt" },
{ $set: { "price.usd": 29.99 } }
)

Resulting document:

[
{
_id: ObjectId("66145f9bcb1d4abffd2f1b50"),
item: 'sweatshirt',
'price.usd': 45.99
quantity: 20,
price: { usd: 29.99 }
}
]

For more examples of updates with aggregation pipelines, see Updates with Aggregation Pipeline.

Back

Dollar Signs