Skip to main content
Version: 1.x

Objects

SurrealDB records can store objects, with no limit to the depth of any nested objects or values within. This means that objects and arrays can be stored within each other in order to model complex data scenarios. Objects can store any value stored within them, and can store different value types within the same object.

CREATE person SET metadata = {
interest_level: 83.67,
information: {
age: 23,
gender: 'm',
},
marketing: true,
activities: [
"clicked link",
"contact form",
"read email",
"viewed website",
"viewed website",
"viewed website",
"read email",
]
};

Object sorting

Objects can be sorted and compared. This is done by first sorting the keys alphabetically.

The next three examples will all return true.

Two objects that are entirely equal, and thus considered to be the same object:

RETURN { date: '2024-01-01', weather: 100 } = { weather: 100, date: '2024-01-01' };

Two objects in which the date key is sorted first, and thus the first is less than the second:

RETURN { date: '2024-01-01', weather: 100 } < { weather: 5, date: '2025-01-01' };

Two objects for which the date key has the same value, and thus the weather key is used for comparison:

 -- The 'weather' key is used to sort, because the 'date' is the same
RETURN { date: '2024-01-01', weather: 100 } < { weather: 10000, date: '2024-01-01' };

As objects can be used as record IDs, attentive key naming can allow you to sort and select ranges of records following the order of the keys you want SurrealDB to compare first.

The measurement records in the example below will always check the attribute key first before date, allowing you to filter by weather station and only then sort by date.

INSERT INTO measurement [
{ id: { attribute: weather_station:1, date: '2024-05-15T04:00:24.420Z' }},
{ id: { attribute: weather_station:1, date: '2024-05-14T04:00:24.420Z' }},
{ id: { attribute: weather_station:1, date: '2024-05-13T04:00:24.420Z' }},
{ id: { attribute: weather_station:2, date: '2024-05-15T04:00:24.420Z' }},
{ id: { attribute: weather_station:2, date: '2024-05-14T04:00:24.420Z' }},
{ id: { attribute: weather_station:2, date: '2024-05-13T04:00:24.420Z' }}
];

LET $start = time::now() - 5y;
LET $end = time::now() + 5y;
LET $ws = weather_station:1;

SELECT * FROM measurement:{ attribute: $ws, date: $start }..={ attribute: $ws, date: $end };
Response
[
{
id: measurement:{
attribute: weather_station:1,
date: '2024-05-13T04:00:24.420Z'
}
},
{
id: measurement:{
attribute: weather_station:1,
date: '2024-05-14T04:00:24.420Z'
}
},
{
id: measurement:{
attribute: weather_station:1,
date: '2024-05-15T04:00:24.420Z'
}
}
]

For more on ID sorting, filtering and ranges, see the page on record IDs.