Skip to main content

Collection

Collection is a third-level unit in Glacier, it corresponds to Collection in MongoDB, and it needs to belong to a Dataset.

To create a Collection, you can use the createCollection method provided by Dataset, and you need to specify the data verification model required to create a Collection, that is, JSON Schema. The sample code is as follows:

src/createCollection.ts
async function createCollection() {
const result = await client
.namespace('myproject')
.dataset('mydataset')
.createCollection('notes', {
title: 'Notes',
type: 'object',
properties: {
title: {
type: 'string',
maxLength: 200,
},
content: {
type: 'string',
maxLength: 5000,
},
createdAt: {
type: 'number',
},
updatedAt: {
type: 'number',
},
},
required: ['title', 'content'],
});
console.log(result);
}

Output result:

{
insertedId: 'notes';
}

Collection is used to store each specific data record. You can get the Collection example to be operated through dataset.collection(name). The operations are addition, deletion, modification, and query. The sample is as follows:

Insert data

src/insertOne.ts
async function insertOne() {
const now = Date.now();
const notes = client
.namespace('myproject')
.dataset('mydataset')
.collection('notes');
const result = await notes.insertOne({
title: `test title`,
content: `test content`,
createdAt: now,
updatedAt: now,
});
console.log(result);
}

Query data

Collection provides a find method, which is analogous to MongoDB and supports most of MongoDB query conditions. Examples are as follows:

src/find.ts
async function find() {
const notes = client
.namespace('myproject')
.dataset('mydataset')
.collection('notes');
const result = await notes
.find({
createdAt: {
$gt: 1668149554498,
},
})
.sort({
createdAt: -1,
})
.skip(0)
.limit(5)
.toArray();
console.log(result);
}

The advanced query syntax currently supported by Glacier SDK is as follows:

  • $eq
  • $gt
  • $gte
  • $in
  • $lt
  • $lte
  • $ne
  • $nin
  • $not
  • $exists
  • $regexp
  • $and
  • $nor
  • $or
caution

In particular, find must call toArray() at the end to get the final query result.

Update data

Collection provides a updateOne method, which is used in a similar way to a combination of find and insertOne. Examples are as follows:

src/updateOne.ts
async function updateOne() {
const now = Date.now();
const result = await myCollection.updateOne(
{
_id: '1',
},
{
updatedAt: now,
}
);
console.log(result);
}
caution

The data update in Glacier is different from MongoDB. Here updateOne is always a partial update rather than replacing the entire record when updating data, which is equivalent to using $set in MongoDB to update the data.

Delete data

Collection provides a deleteOne method, which is similar to the find method. The example is as follows:

src/deleteOne.ts
async function deleteOne() {
const now = Date.now();
const result = await myCollection.deleteOne({
_id: '1',
});
console.log(result);
}