$date in collections
-
Python
-
TypeScript
-
Java
-
curl
The handling of datetime objects, with particular emphasis on usage of naive (i.e. timezone-unaware) datetimes, changed in the Python client version 2.0-preview. If you are using client version 2.0-preview or later, see the description of this change in Data API client upgrade guide. |
Date and datetime objects are instances of the Python standard library datetime.datetime
and datetime.date
classes that you can use anywhere in documents.
The following example uses dates in insert
, update
, and find
commands.
Read operations from a collection always return the datetime
class, regardless of whether the original command used date
or datetime
.
import datetime
from astrapy import DataAPIClient
from astrapy.ids import ObjectId, uuid8, UUID
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")
collection = database.my_collection
# Insert documents containing date and datetime values:
collection.insert_one({"when": datetime.datetime.now()})
collection.insert_one({"date_of_birth": datetime.date(2000, 1, 1)})
collection.insert_one({"registered_at": datetime.date(1999, 11, 14)})
# Update a document, using a date in the filter:
collection.update_one(
{"registered_at": datetime.date(1999, 11, 14)},
{"$set": {"message": "happy Sunday!"}},
)
# Update a document, setting "last_reviewed" to the current date:
collection.update_one(
{"date_of_birth": {"$exists": True}},
{"$currentDate": {"last_reviewed": True}},
)
# Find documents by inequality on a date value:
print(
collection.find_one(
{"date_of_birth": {"$lt": datetime.date(2001, 1, 1)}},
projection={"_id": False},
)
)
# will print:
# {'date_of_birth': datetime.datetime(2000, 1, 1, 0, 0), 'last_reviewed': datetime.datetime(...now...)}
You can use standard JS Date
objects anywhere in documents to represent dates and times.
Read operations also return Date
objects for document fields stored using { $date: number }
.
The following example uses dates in insert
, update
, and find
commands:
import { DataAPIClient } from '@datastax/astra-db-ts';
// Reference an untyped collection
const client = new DataAPIClient('TOKEN');
const db = client.db('ENDPOINT', { keyspace: 'KEYSPACE' });
(async function () {
// Create an untyped collection
const collection = await db.createCollection('dates_test');
// Insert documents with some dates
await collection.insertOne({ dateOfBirth: new Date(1394104654000) });
await collection.insertOne({ dateOfBirth: new Date('1863-05-28') });
// Update a document with a date and setting lastModified to now
await collection.updateOne(
{
dateOfBirth: new Date('1863-05-28'),
},
{
$set: { message: 'Happy Birthday!' },
$currentDate: { lastModified: true },
},
);
// Will print around new Date()
const found = await collection.findOne({ dateOfBirth: { $lt: new Date('1900-01-01') } });
console.log(found?.lastModified);
})();
The Data API uses the ejson
standard to represents time-related objects.
The Java client introduces custom serializers as three types of objects: java.util.Date
, java.util.Calendar
, java.util.Instant
.
You can use these objects in documents as well as filter clauses and update clauses.
The following example uses dates in insert
, update
, and find
commands:
package com.datastax.astra.client.collection;
import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.FindOneOptions;
import com.datastax.astra.client.model.Projections;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import static com.datastax.astra.client.model.Filters.eq;
import static com.datastax.astra.client.model.Filters.lt;
import static com.datastax.astra.client.model.Updates.set;
public class WorkingWithDates {
public static void main(String[] args) {
// Given an existing collection
Collection<Document> collection = new DataAPIClient("TOKEN")
.getDatabase("API_ENDPOINT")
.getCollection("COLLECTION_NAME");
Calendar c = Calendar.getInstance();
collection.insertOne(new Document().append("registered_at", c));
collection.insertOne(new Document().append("date_of_birth", new Date()));
collection.insertOne(new Document().append("just_a_date", Instant.now()));
collection.updateOne(
eq("registered_at", c), // filter clause
set("message", "happy Sunday!")); // update clause
collection.findOne(
lt("date_of_birth", new Date(System.currentTimeMillis() - 1000 * 1000)),
new FindOneOptions().projection(Projections.exclude("_id")));
}
}
You can use $date
to represent dates as Unix timestamps in the JSON payload of a Data API command:
"date_of_birth": { "$date": 1690045891 }
The following example includes a date in an insertOne
command:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"insertOne": {
"document": {
"$vector": [0.25, 0.25, 0.25, 0.25, 0.25],
"date_of_birth": { "$date": 1690045891 }
}
}
}' | jq
The following example uses the date to find and update a document with the updateOne
command:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"updateOne": {
"filter": {
"date_of_birth": { "$date": 1690045891 }
},
"update": { "$set": { "message": "Happy birthday!" } }
}
}' | jq
The following example uses the $currentDate
update operator to set a property to the current date:
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"findOneAndUpdate": {
"filter": { "_id": "doc1" },
"update": {
"$currentDate": {
"createdAt": true
}
}
}
}' | jq