@mastra/chroma 0.0.0-switch-to-core-20250424015131 → 0.0.0-vector-query-sources-20250516172905

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@ describe('ChromaVector Integration Tests', () => {
16
16
  beforeEach(async () => {
17
17
  // Clean up any existing test index
18
18
  try {
19
- await vectorDB.deleteIndex(testIndexName);
19
+ await vectorDB.deleteIndex({ indexName: testIndexName });
20
20
  } catch {
21
21
  // Ignore errors if index doesn't exist
22
22
  }
@@ -26,7 +26,7 @@ describe('ChromaVector Integration Tests', () => {
26
26
  afterEach(async () => {
27
27
  // Cleanup after tests
28
28
  try {
29
- await vectorDB.deleteIndex(testIndexName);
29
+ await vectorDB.deleteIndex({ indexName: testIndexName });
30
30
  } catch {
31
31
  // Ignore cleanup errors
32
32
  }
@@ -39,14 +39,14 @@ describe('ChromaVector Integration Tests', () => {
39
39
  });
40
40
 
41
41
  it('should describe index correctly', async () => {
42
- const stats: IndexStats = await vectorDB.describeIndex(testIndexName);
42
+ const stats: IndexStats = await vectorDB.describeIndex({ indexName: testIndexName });
43
43
  expect(stats.dimension).toBe(dimension);
44
44
  expect(stats.count).toBe(0);
45
45
  expect(stats.metric).toBe('cosine');
46
46
  });
47
47
 
48
48
  it('should delete index', async () => {
49
- await vectorDB.deleteIndex(testIndexName);
49
+ await vectorDB.deleteIndex({ indexName: testIndexName });
50
50
  const indexes = await vectorDB.listIndexes();
51
51
  expect(indexes).not.toContain(testIndexName);
52
52
  });
@@ -58,10 +58,10 @@ describe('ChromaVector Integration Tests', () => {
58
58
  const testIndex = `test-index-${metric}`;
59
59
  await vectorDB.createIndex({ indexName: testIndex, dimension, metric });
60
60
 
61
- const stats = await vectorDB.describeIndex(testIndex);
61
+ const stats = await vectorDB.describeIndex({ indexName: testIndex });
62
62
  expect(stats.metric).toBe(metric);
63
63
 
64
- await vectorDB.deleteIndex(testIndex);
64
+ await vectorDB.deleteIndex({ indexName: testIndex });
65
65
  }
66
66
  });
67
67
  });
@@ -80,14 +80,14 @@ describe('ChromaVector Integration Tests', () => {
80
80
  expect(ids).toHaveLength(testVectors.length);
81
81
  ids.forEach(id => expect(typeof id).toBe('string'));
82
82
 
83
- const stats = await vectorDB.describeIndex(testIndexName);
83
+ const stats = await vectorDB.describeIndex({ indexName: testIndexName });
84
84
  expect(stats.count).toBe(testVectors.length);
85
85
  });
86
86
 
87
87
  it('should upsert vectors with provided ids and metadata', async () => {
88
88
  await vectorDB.upsert({ indexName: testIndexName, vectors: testVectors, metadata: testMetadata, ids: testIds });
89
89
 
90
- const stats = await vectorDB.describeIndex(testIndexName);
90
+ const stats = await vectorDB.describeIndex({ indexName: testIndexName });
91
91
  expect(stats.count).toBe(testVectors.length);
92
92
 
93
93
  // Query each vector to verify metadata
@@ -133,7 +133,7 @@ describe('ChromaVector Integration Tests', () => {
133
133
  metadata: newMetaData,
134
134
  };
135
135
 
136
- await vectorDB.updateIndexById(testIndexName, idToBeUpdated, update);
136
+ await vectorDB.updateVector({ indexName: testIndexName, id: idToBeUpdated, update });
137
137
 
138
138
  const results: QueryResult[] = await vectorDB.query({
139
139
  indexName: testIndexName,
@@ -159,7 +159,7 @@ describe('ChromaVector Integration Tests', () => {
159
159
  metadata: newMetaData,
160
160
  };
161
161
 
162
- await vectorDB.updateIndexById(testIndexName, idToBeUpdated, update);
162
+ await vectorDB.updateVector({ indexName: testIndexName, id: idToBeUpdated, update });
163
163
 
164
164
  const results: QueryResult[] = await vectorDB.query({
165
165
  indexName: testIndexName,
@@ -183,7 +183,7 @@ describe('ChromaVector Integration Tests', () => {
183
183
  vector: newVector,
184
184
  };
185
185
 
186
- await vectorDB.updateIndexById(testIndexName, idToBeUpdated, update);
186
+ await vectorDB.updateVector({ indexName: testIndexName, id: idToBeUpdated, update });
187
187
 
188
188
  const results: QueryResult[] = await vectorDB.query({
189
189
  indexName: testIndexName,
@@ -196,7 +196,9 @@ describe('ChromaVector Integration Tests', () => {
196
196
  });
197
197
 
198
198
  it('should throw exception when no updates are given', async () => {
199
- await expect(vectorDB.updateIndexById(testIndexName, 'id', {})).rejects.toThrow('No updates provided');
199
+ await expect(vectorDB.updateVector({ indexName: testIndexName, id: 'id', update: {} })).rejects.toThrow(
200
+ 'No updates provided',
201
+ );
200
202
  });
201
203
 
202
204
  it('should delete the vector by id', async () => {
@@ -204,7 +206,7 @@ describe('ChromaVector Integration Tests', () => {
204
206
  expect(ids).toHaveLength(3);
205
207
  const idToBeDeleted = ids[0];
206
208
 
207
- await vectorDB.deleteIndexById(testIndexName, idToBeDeleted);
209
+ await vectorDB.deleteVector({ indexName: testIndexName, id: idToBeDeleted });
208
210
 
209
211
  const results: QueryResult[] = await vectorDB.query({
210
212
  indexName: testIndexName,
@@ -273,8 +275,17 @@ describe('ChromaVector Integration Tests', () => {
273
275
  });
274
276
 
275
277
  describe('Error Handling', () => {
278
+ const testIndexName = 'test_index_error';
279
+ beforeAll(async () => {
280
+ await vectorDB.createIndex({ indexName: testIndexName, dimension: 3 });
281
+ });
282
+
283
+ afterAll(async () => {
284
+ await vectorDB.deleteIndex({ indexName: testIndexName });
285
+ });
286
+
276
287
  it('should handle non-existent index queries', async () => {
277
- await expect(vectorDB.query({ indexName: 'non-existent-index-yu', queryVector: [1, 2, 3] })).rejects.toThrow();
288
+ await expect(vectorDB.query({ indexName: 'non-existent-index', queryVector: [1, 2, 3] })).rejects.toThrow();
278
289
  });
279
290
 
280
291
  it('should handle invalid dimension vectors', async () => {
@@ -282,10 +293,59 @@ describe('ChromaVector Integration Tests', () => {
282
293
  await expect(vectorDB.upsert({ indexName: testIndexName, vectors: [invalidVector] })).rejects.toThrow();
283
294
  });
284
295
 
285
- it('should handle mismatched metadata and vectors length', async () => {
286
- const vectors = [[1, 2, 3]];
287
- const metadata = [{}, {}]; // More metadata than vectors
288
- await expect(vectorDB.upsert({ indexName: testIndexName, vectors, metadata })).rejects.toThrow();
296
+ it('should handle duplicate index creation gracefully', async () => {
297
+ const infoSpy = vi.spyOn(vectorDB['logger'], 'info');
298
+ const warnSpy = vi.spyOn(vectorDB['logger'], 'warn');
299
+
300
+ const duplicateIndexName = `duplicate-test`;
301
+ const dimension = 768;
302
+
303
+ try {
304
+ // Create index first time
305
+ await vectorDB.createIndex({
306
+ indexName: duplicateIndexName,
307
+ dimension,
308
+ metric: 'cosine',
309
+ });
310
+
311
+ // Try to create with same dimensions - should not throw
312
+ await expect(
313
+ vectorDB.createIndex({
314
+ indexName: duplicateIndexName,
315
+ dimension,
316
+ metric: 'cosine',
317
+ }),
318
+ ).resolves.not.toThrow();
319
+
320
+ expect(infoSpy).toHaveBeenCalledWith(expect.stringContaining('already exists with'));
321
+
322
+ // Try to create with same dimensions and different metric - should not throw
323
+ await expect(
324
+ vectorDB.createIndex({
325
+ indexName: duplicateIndexName,
326
+ dimension,
327
+ metric: 'euclidean',
328
+ }),
329
+ ).resolves.not.toThrow();
330
+
331
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Attempted to create index with metric'));
332
+
333
+ // Try to create with different dimensions - should throw
334
+ await expect(
335
+ vectorDB.createIndex({
336
+ indexName: duplicateIndexName,
337
+ dimension: dimension + 1,
338
+ metric: 'cosine',
339
+ }),
340
+ ).rejects.toThrow(
341
+ `Index "${duplicateIndexName}" already exists with ${dimension} dimensions, but ${dimension + 1} dimensions were requested`,
342
+ );
343
+ } finally {
344
+ infoSpy.mockRestore();
345
+ warnSpy.mockRestore();
346
+ // Cleanup
347
+ await vectorDB.deleteIndex({ indexName: duplicateIndexName });
348
+ }
289
349
  });
290
350
  });
291
351
 
@@ -461,7 +521,7 @@ describe('ChromaVector Integration Tests', () => {
461
521
  // Set up test vectors and metadata
462
522
  beforeAll(async () => {
463
523
  try {
464
- await vectorDB.deleteIndex(testIndexName2);
524
+ await vectorDB.deleteIndex({ indexName: testIndexName2 });
465
525
  } catch {
466
526
  // Ignore errors if index doesn't exist
467
527
  }
@@ -509,7 +569,7 @@ describe('ChromaVector Integration Tests', () => {
509
569
  afterAll(async () => {
510
570
  // Cleanup after tests
511
571
  try {
512
- await vectorDB.deleteIndex(testIndexName2);
572
+ await vectorDB.deleteIndex({ indexName: testIndexName2 });
513
573
  } catch {
514
574
  // Ignore cleanup errors
515
575
  }
@@ -1180,7 +1240,7 @@ describe('ChromaVector Integration Tests', () => {
1180
1240
 
1181
1241
  beforeAll(async () => {
1182
1242
  try {
1183
- await vectorDB.deleteIndex(testIndexName3);
1243
+ await vectorDB.deleteIndex({ indexName: testIndexName3 });
1184
1244
  } catch {
1185
1245
  // Ignore errors if index doesn't exist
1186
1246
  }
@@ -1214,7 +1274,7 @@ describe('ChromaVector Integration Tests', () => {
1214
1274
  afterAll(async () => {
1215
1275
  // Cleanup after tests
1216
1276
  try {
1217
- await vectorDB.deleteIndex(testIndexName3);
1277
+ await vectorDB.deleteIndex({ indexName: testIndexName3 });
1218
1278
  } catch {
1219
1279
  // Ignore cleanup errors
1220
1280
  }
@@ -1410,17 +1470,17 @@ describe('ChromaVector Integration Tests', () => {
1410
1470
  let warnSpy;
1411
1471
 
1412
1472
  beforeAll(async () => {
1413
- await vectorDB.createIndex({ indexName: indexName, dimension: 3 });
1473
+ await vectorDB.createIndex({ indexName, dimension: 3 });
1414
1474
  });
1415
1475
 
1416
1476
  afterAll(async () => {
1417
1477
  try {
1418
- await vectorDB.deleteIndex(indexName);
1478
+ await vectorDB.deleteIndex({ indexName });
1419
1479
  } catch {
1420
1480
  // Ignore errors if index doesn't exist
1421
1481
  }
1422
1482
  try {
1423
- await vectorDB.deleteIndex(indexName2);
1483
+ await vectorDB.deleteIndex({ indexName: indexName2 });
1424
1484
  } catch {
1425
1485
  // Ignore errors if index doesn't exist
1426
1486
  }
@@ -1433,7 +1493,7 @@ describe('ChromaVector Integration Tests', () => {
1433
1493
  afterEach(async () => {
1434
1494
  warnSpy.mockRestore();
1435
1495
  try {
1436
- await vectorDB.deleteIndex(indexName2);
1496
+ await vectorDB.deleteIndex({ indexName: indexName2 });
1437
1497
  } catch {
1438
1498
  // Ignore errors if index doesn't exist
1439
1499
  }
@@ -1517,7 +1577,7 @@ describe('ChromaVector Integration Tests', () => {
1517
1577
 
1518
1578
  beforeEach(async () => {
1519
1579
  try {
1520
- await vectorDB.deleteIndex(perfTestIndex);
1580
+ await vectorDB.deleteIndex({ indexName: perfTestIndex });
1521
1581
  } catch {
1522
1582
  // Ignore errors if index doesn't exist
1523
1583
  }
@@ -1526,7 +1586,7 @@ describe('ChromaVector Integration Tests', () => {
1526
1586
 
1527
1587
  afterEach(async () => {
1528
1588
  try {
1529
- await vectorDB.deleteIndex(perfTestIndex);
1589
+ await vectorDB.deleteIndex({ indexName: perfTestIndex });
1530
1590
  } catch {
1531
1591
  // Ignore cleanup errors
1532
1592
  }
@@ -1569,7 +1629,7 @@ describe('ChromaVector Integration Tests', () => {
1569
1629
  });
1570
1630
 
1571
1631
  // Verify all vectors were inserted
1572
- const stats = await vectorDB.describeIndex(perfTestIndex);
1632
+ const stats = await vectorDB.describeIndex({ indexName: perfTestIndex });
1573
1633
  expect(stats.count).toBe(batchSize);
1574
1634
 
1575
1635
  const results = await vectorDB.query({
@@ -8,6 +8,10 @@ import type {
8
8
  ParamsToArgs,
9
9
  QueryVectorArgs,
10
10
  UpsertVectorArgs,
11
+ DescribeIndexParams,
12
+ DeleteIndexParams,
13
+ DeleteVectorParams,
14
+ UpdateVectorParams,
11
15
  } from '@mastra/core/vector';
12
16
 
13
17
  import type { VectorFilter } from '@mastra/core/vector/filter';
@@ -80,7 +84,7 @@ export class ChromaVector extends MastraVector {
80
84
  const collection = await this.getCollection(indexName);
81
85
 
82
86
  // Get index stats to check dimension
83
- const stats = await this.describeIndex(indexName);
87
+ const stats = await this.describeIndex({ indexName });
84
88
 
85
89
  // Validate vector dimensions
86
90
  this.validateVectorDimensions(vectors, stats.dimension);
@@ -111,7 +115,6 @@ export class ChromaVector extends MastraVector {
111
115
 
112
116
  async createIndex(...args: ParamsToArgs<CreateIndexParams>): Promise<void> {
113
117
  const params = this.normalizeArgs<CreateIndexParams>('createIndex', args);
114
-
115
118
  const { indexName, dimension, metric = 'cosine' } = params;
116
119
 
117
120
  if (!Number.isInteger(dimension) || dimension <= 0) {
@@ -121,13 +124,24 @@ export class ChromaVector extends MastraVector {
121
124
  if (!['cosine', 'l2', 'ip'].includes(hnswSpace)) {
122
125
  throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
123
126
  }
124
- await this.client.createCollection({
125
- name: indexName,
126
- metadata: {
127
- dimension,
128
- 'hnsw:space': this.HnswSpaceMap[metric],
129
- },
130
- });
127
+ try {
128
+ await this.client.createCollection({
129
+ name: indexName,
130
+ metadata: {
131
+ dimension,
132
+ 'hnsw:space': hnswSpace,
133
+ },
134
+ });
135
+ } catch (error: any) {
136
+ // Check for 'already exists' error
137
+ const message = error?.message || error?.toString();
138
+ if (message && message.toLowerCase().includes('already exists')) {
139
+ // Fetch collection info and check dimension
140
+ await this.validateExistingIndex(indexName, dimension, metric);
141
+ return;
142
+ }
143
+ throw error;
144
+ }
131
145
  }
132
146
 
133
147
  transformFilter(filter?: VectorFilter) {
@@ -167,7 +181,17 @@ export class ChromaVector extends MastraVector {
167
181
  return collections.map(collection => collection);
168
182
  }
169
183
 
170
- async describeIndex(indexName: string): Promise<IndexStats> {
184
+ /**
185
+ * Retrieves statistics about a vector index.
186
+ *
187
+ * @param params - The parameters for describing an index
188
+ * @param params.indexName - The name of the index to describe
189
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
190
+ */
191
+ async describeIndex(...args: ParamsToArgs<DescribeIndexParams>): Promise<IndexStats> {
192
+ const params = this.normalizeArgs<DescribeIndexParams>('describeIndex', args);
193
+ const { indexName } = params;
194
+
171
195
  const collection = await this.getCollection(indexName);
172
196
  const count = await collection.count();
173
197
  const metadata = collection.metadata;
@@ -181,41 +205,108 @@ export class ChromaVector extends MastraVector {
181
205
  };
182
206
  }
183
207
 
184
- async deleteIndex(indexName: string): Promise<void> {
208
+ async deleteIndex(...args: ParamsToArgs<DeleteIndexParams>): Promise<void> {
209
+ const params = this.normalizeArgs<DeleteIndexParams>('deleteIndex', args);
210
+ const { indexName } = params;
185
211
  await this.client.deleteCollection({ name: indexName });
186
212
  this.collections.delete(indexName);
187
213
  }
188
214
 
215
+ /**
216
+ * @deprecated Use {@link updateVector} instead. This method will be removed on May 20th, 2025.
217
+ *
218
+ * Updates a vector by its ID with the provided vector and/or metadata.
219
+ * @param indexName - The name of the index containing the vector.
220
+ * @param id - The ID of the vector to update.
221
+ * @param update - An object containing the vector and/or metadata to update.
222
+ * @param update.vector - An optional array of numbers representing the new vector.
223
+ * @param update.metadata - An optional record containing the new metadata.
224
+ * @returns A promise that resolves when the update is complete.
225
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
226
+ */
189
227
  async updateIndexById(
190
228
  indexName: string,
191
229
  id: string,
192
230
  update: { vector?: number[]; metadata?: Record<string, any> },
193
231
  ): Promise<void> {
194
- if (!update.vector && !update.metadata) {
195
- throw new Error('No updates provided');
196
- }
232
+ this.logger.warn(
233
+ `Deprecation Warning: updateIndexById() is deprecated.
234
+ Please use updateVector() instead.
235
+ updateIndexById() will be removed on May 20th, 2025.`,
236
+ );
237
+ await this.updateVector({ indexName, id, update });
238
+ }
197
239
 
198
- const collection: Collection = await this.getCollection(indexName, true);
240
+ /**
241
+ * Updates a vector by its ID with the provided vector and/or metadata.
242
+ * @param indexName - The name of the index containing the vector.
243
+ * @param id - The ID of the vector to update.
244
+ * @param update - An object containing the vector and/or metadata to update.
245
+ * @param update.vector - An optional array of numbers representing the new vector.
246
+ * @param update.metadata - An optional record containing the new metadata.
247
+ * @returns A promise that resolves when the update is complete.
248
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
249
+ */
250
+ async updateVector(...args: ParamsToArgs<UpdateVectorParams>): Promise<void> {
251
+ const params = this.normalizeArgs<UpdateVectorParams>('updateVector', args);
252
+ const { indexName, id, update } = params;
253
+ try {
254
+ if (!update.vector && !update.metadata) {
255
+ throw new Error('No updates provided');
256
+ }
199
257
 
200
- const updateOptions: UpdateRecordsParams = { ids: [id] };
258
+ const collection: Collection = await this.getCollection(indexName, true);
201
259
 
202
- if (update?.vector) {
203
- updateOptions.embeddings = [update.vector];
204
- }
260
+ const updateOptions: UpdateRecordsParams = { ids: [id] };
205
261
 
206
- if (update?.metadata) {
207
- updateOptions.metadatas = [update.metadata];
208
- }
262
+ if (update?.vector) {
263
+ const stats = await this.describeIndex({ indexName });
264
+ this.validateVectorDimensions([update.vector], stats.dimension);
265
+ updateOptions.embeddings = [update.vector];
266
+ }
267
+
268
+ if (update?.metadata) {
269
+ updateOptions.metadatas = [update.metadata];
270
+ }
209
271
 
210
- return await collection.update(updateOptions);
272
+ return await collection.update(updateOptions);
273
+ } catch (error: any) {
274
+ throw new Error(`Failed to update vector by id: ${id} for index name: ${indexName}: ${error.message}`);
275
+ }
211
276
  }
212
277
 
278
+ /**
279
+ * @deprecated Use {@link deleteVector} instead. This method will be removed on May 20th, 2025.
280
+ *
281
+ * Deletes a vector by its ID.
282
+ * @param indexName - The name of the index containing the vector.
283
+ * @param id - The ID of the vector to delete.
284
+ * @returns A promise that resolves when the deletion is complete.
285
+ * @throws Will throw an error if the deletion operation fails.
286
+ */
213
287
  async deleteIndexById(indexName: string, id: string): Promise<void> {
288
+ this.logger.warn(
289
+ `Deprecation Warning: deleteIndexById() is deprecated. Please use deleteVector() instead. deleteIndexById() will be removed on May 20th.`,
290
+ );
291
+ await this.deleteVector(indexName, id);
292
+ }
293
+
294
+ /**
295
+ * Deletes a vector by its ID.
296
+ * @param indexName - The name of the index containing the vector.
297
+ * @param id - The ID of the vector to delete.
298
+ * @returns A promise that resolves when the deletion is complete.
299
+ * @throws Will throw an error if the deletion operation fails.
300
+ */
301
+ async deleteVector(...args: ParamsToArgs<DeleteVectorParams>): Promise<void> {
302
+ const params = this.normalizeArgs<DeleteVectorParams>('deleteVector', args);
303
+
304
+ const { indexName, id } = params;
214
305
  try {
215
306
  const collection: Collection = await this.getCollection(indexName, true);
216
307
  await collection.delete({ ids: [id] });
217
308
  } catch (error: any) {
218
- throw new Error(`Failed to delete index by id: ${id} for index name: ${indexName}: ${error.message}`);
309
+ throw new Error(`Failed to delete vector by id: ${id} for index name: ${indexName}: ${error.message}`);
219
310
  }
220
311
  }
221
312
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Vector store specific prompt that details supported operators and examples.
3
+ * This prompt helps users construct valid filters for Chroma Vector.
4
+ */
5
+ export const CHROMA_PROMPT = `When querying Chroma, you can ONLY use the operators listed below. Any other operators will be rejected.
6
+ Important: Don't explain how to construct the filter - use the specified operators and fields to search the content and return relevant results.
7
+ If a user tries to give an explicit operator that is not supported, reject the filter entirely and let them know that the operator is not supported.
8
+
9
+ Basic Comparison Operators:
10
+ - $eq: Exact match (default when using field: value)
11
+ Example: { "category": "electronics" }
12
+ - $ne: Not equal
13
+ Example: { "category": { "$ne": "electronics" } }
14
+ - $gt: Greater than
15
+ Example: { "price": { "$gt": 100 } }
16
+ - $gte: Greater than or equal
17
+ Example: { "price": { "$gte": 100 } }
18
+ - $lt: Less than
19
+ Example: { "price": { "$lt": 100 } }
20
+ - $lte: Less than or equal
21
+ Example: { "price": { "$lte": 100 } }
22
+
23
+ Array Operators:
24
+ - $in: Match any value in array
25
+ Example: { "category": { "$in": ["electronics", "books"] } }
26
+ - $nin: Does not match any value in array
27
+ Example: { "category": { "$nin": ["electronics", "books"] } }
28
+
29
+ Logical Operators:
30
+ - $and: Logical AND
31
+ Example: { "$and": [{ "price": { "$gt": 100 } }, { "category": "electronics" }] }
32
+ - $or: Logical OR
33
+ Example: { "$or": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
34
+
35
+ Restrictions:
36
+ - Regex patterns are not supported
37
+ - Element operators are not supported
38
+ - Only $and and $or logical operators are supported
39
+ - Nested fields are supported using dot notation
40
+ - Multiple conditions on the same field are supported with both implicit and explicit $and
41
+ - Empty arrays in $in/$nin will return no results
42
+ - If multiple top-level fields exist, they're wrapped in $and
43
+ - Only logical operators ($and, $or) can be used at the top level
44
+ - All other operators must be used within a field condition
45
+ Valid: { "field": { "$gt": 100 } }
46
+ Valid: { "$and": [...] }
47
+ Invalid: { "$gt": 100 }
48
+ Invalid: { "$in": [...] }
49
+ - Logical operators must contain field conditions, not direct operators
50
+ Valid: { "$and": [{ "field": { "$gt": 100 } }] }
51
+ Invalid: { "$and": [{ "$gt": 100 }] }
52
+ - Logical operators ($and, $or):
53
+ - Can only be used at top level or nested within other logical operators
54
+ - Can not be used on a field level, or be nested inside a field
55
+ - Can not be used inside an operator
56
+ - Valid: { "$and": [{ "field": { "$gt": 100 } }] }
57
+ - Valid: { "$or": [{ "$and": [{ "field": { "$gt": 100 } }] }] }
58
+ - Invalid: { "field": { "$and": [{ "$gt": 100 }] } }
59
+ - Invalid: { "field": { "$or": [{ "$gt": 100 }] } }
60
+ - Invalid: { "field": { "$gt": { "$and": [{...}] } } }
61
+
62
+ Example Complex Query:
63
+ {
64
+ "$and": [
65
+ { "category": { "$in": ["electronics", "computers"] } },
66
+ { "price": { "$gte": 100, "$lte": 1000 } },
67
+ { "$or": [
68
+ { "inStock": true },
69
+ { "preorder": true }
70
+ ]}
71
+ ]
72
+ }`;