0
# Document Operations
1
2
Core key-value operations for creating, reading, updating, and deleting documents in Couchbase collections. These operations form the foundation of data manipulation in Couchbase.
3
4
## Capabilities
5
6
### Basic Document Operations
7
8
Fundamental CRUD operations for document management.
9
10
```python { .api }
11
class CBCollection:
12
def get(self, key: str, options: GetOptions = None) -> GetResult:
13
"""
14
Retrieve a document by key.
15
16
Args:
17
key (str): Document key
18
options (GetOptions, optional): Retrieval options
19
20
Returns:
21
GetResult: Document content and metadata
22
23
Raises:
24
DocumentNotFoundException: If document doesn't exist
25
"""
26
27
def upsert(self, key: str, value: Any, options: UpsertOptions = None) -> MutationResult:
28
"""
29
Insert or update a document.
30
31
Args:
32
key (str): Document key
33
value (Any): Document content
34
options (UpsertOptions, optional): Upsert options
35
36
Returns:
37
MutationResult: Operation result with CAS and mutation token
38
39
Raises:
40
TimeoutException: If operation times out
41
"""
42
43
def insert(self, key: str, value: Any, options: InsertOptions = None) -> MutationResult:
44
"""
45
Insert a new document.
46
47
Args:
48
key (str): Document key
49
value (Any): Document content
50
options (InsertOptions, optional): Insert options
51
52
Returns:
53
MutationResult: Operation result with CAS and mutation token
54
55
Raises:
56
DocumentExistsException: If document already exists
57
"""
58
59
def replace(self, key: str, value: Any, options: ReplaceOptions = None) -> MutationResult:
60
"""
61
Replace an existing document.
62
63
Args:
64
key (str): Document key
65
value (Any): New document content
66
options (ReplaceOptions, optional): Replace options
67
68
Returns:
69
MutationResult: Operation result with CAS and mutation token
70
71
Raises:
72
DocumentNotFoundException: If document doesn't exist
73
CASMismatchException: If CAS value doesn't match
74
"""
75
76
def remove(self, key: str, options: RemoveOptions = None) -> MutationResult:
77
"""
78
Remove a document.
79
80
Args:
81
key (str): Document key
82
options (RemoveOptions, optional): Remove options
83
84
Returns:
85
MutationResult: Operation result with CAS and mutation token
86
87
Raises:
88
DocumentNotFoundException: If document doesn't exist
89
CASMismatchException: If CAS value doesn't match
90
"""
91
```
92
93
### Document Metadata Operations
94
95
Operations for working with document metadata without retrieving content.
96
97
```python { .api }
98
class CBCollection:
99
def exists(self, key: str, options: ExistsOptions = None) -> ExistsResult:
100
"""
101
Check if a document exists.
102
103
Args:
104
key (str): Document key
105
options (ExistsOptions, optional): Existence check options
106
107
Returns:
108
ExistsResult: Existence status and CAS value
109
"""
110
111
def touch(self, key: str, expiry: timedelta, options: TouchOptions = None) -> MutationResult:
112
"""
113
Update document expiration time.
114
115
Args:
116
key (str): Document key
117
expiry (timedelta): New expiration time
118
options (TouchOptions, optional): Touch options
119
120
Returns:
121
MutationResult: Operation result with new CAS
122
123
Raises:
124
DocumentNotFoundException: If document doesn't exist
125
"""
126
127
def get_and_touch(self, key: str, expiry: timedelta, options: GetAndTouchOptions = None) -> GetResult:
128
"""
129
Retrieve document and update expiration.
130
131
Args:
132
key (str): Document key
133
expiry (timedelta): New expiration time
134
options (GetAndTouchOptions, optional): Operation options
135
136
Returns:
137
GetResult: Document content with updated CAS
138
139
Raises:
140
DocumentNotFoundException: If document doesn't exist
141
"""
142
143
def get_and_lock(self, key: str, lock_time: timedelta, options: GetAndLockOptions = None) -> GetResult:
144
"""
145
Retrieve and lock a document.
146
147
Args:
148
key (str): Document key
149
lock_time (timedelta): Lock duration
150
options (GetAndLockOptions, optional): Lock options
151
152
Returns:
153
GetResult: Document content with lock CAS
154
155
Raises:
156
DocumentNotFoundException: If document doesn't exist
157
DocumentLockedException: If document is already locked
158
"""
159
160
def unlock(self, key: str, cas: int, options: UnlockOptions = None) -> None:
161
"""
162
Unlock a locked document.
163
164
Args:
165
key (str): Document key
166
cas (int): CAS value from get_and_lock
167
options (UnlockOptions, optional): Unlock options
168
169
Raises:
170
DocumentNotFoundException: If document doesn't exist
171
CASMismatchException: If CAS value doesn't match
172
"""
173
174
def get_any_replica(self, key: str, options: GetAnyReplicaOptions = None) -> GetReplicaResult:
175
"""
176
Retrieve a document from any available replica.
177
178
Args:
179
key (str): Document key
180
options (GetAnyReplicaOptions, optional): Replica retrieval options
181
182
Returns:
183
GetReplicaResult: Document content from replica with replica flag
184
185
Raises:
186
DocumentNotFoundException: If document doesn't exist on any replica
187
"""
188
189
def get_all_replicas(self, key: str, options: GetAllReplicasOptions = None) -> List[GetReplicaResult]:
190
"""
191
Retrieve a document from all available replicas.
192
193
Args:
194
key (str): Document key
195
options (GetAllReplicasOptions, optional): Replica retrieval options
196
197
Returns:
198
List[GetReplicaResult]: Document content from all replicas
199
200
Raises:
201
DocumentNotFoundException: If document doesn't exist
202
"""
203
```
204
205
### Binary Operations
206
207
Operations for working with binary data and counter documents.
208
209
```python { .api }
210
class BinaryCollection:
211
def append(self, key: str, value: bytes, options: AppendOptions = None) -> MutationResult:
212
"""
213
Append binary data to document.
214
215
Args:
216
key (str): Document key
217
value (bytes): Binary data to append
218
options (AppendOptions, optional): Append options
219
220
Returns:
221
MutationResult: Operation result
222
223
Raises:
224
DocumentNotFoundException: If document doesn't exist
225
"""
226
227
def prepend(self, key: str, value: bytes, options: PrependOptions = None) -> MutationResult:
228
"""
229
Prepend binary data to document.
230
231
Args:
232
key (str): Document key
233
value (bytes): Binary data to prepend
234
options (PrependOptions, optional): Prepend options
235
236
Returns:
237
MutationResult: Operation result
238
239
Raises:
240
DocumentNotFoundException: If document doesn't exist
241
"""
242
243
def increment(self, key: str, options: IncrementOptions = None) -> CounterResult:
244
"""
245
Increment a counter document.
246
247
Args:
248
key (str): Counter document key
249
options (IncrementOptions, optional): Increment options
250
251
Returns:
252
CounterResult: New counter value and CAS
253
254
Raises:
255
DocumentNotFoundException: If document doesn't exist and no initial value set
256
"""
257
258
def decrement(self, key: str, options: DecrementOptions = None) -> CounterResult:
259
"""
260
Decrement a counter document.
261
262
Args:
263
key (str): Counter document key
264
options (DecrementOptions, optional): Decrement options
265
266
Returns:
267
CounterResult: New counter value and CAS
268
269
Raises:
270
DocumentNotFoundException: If document doesn't exist and no initial value set
271
"""
272
```
273
274
### Multi-Document Operations
275
276
Batch operations for improved performance when working with multiple documents.
277
278
```python { .api }
279
class CBCollection:
280
def get_multi(self, keys: List[str], options: GetOptions = None) -> MultiGetResult:
281
"""
282
Retrieve multiple documents.
283
284
Args:
285
keys (List[str]): List of document keys
286
options (GetOptions, optional): Retrieval options
287
288
Returns:
289
MultiGetResult: Results for each key
290
"""
291
292
def upsert_multi(self, docs: Dict[str, Any], options: UpsertOptions = None) -> MultiMutationResult:
293
"""
294
Upsert multiple documents.
295
296
Args:
297
docs (Dict[str, Any]): Key-value pairs to upsert
298
options (UpsertOptions, optional): Upsert options
299
300
Returns:
301
MultiMutationResult: Results for each key
302
"""
303
304
def remove_multi(self, keys: List[str], options: RemoveOptions = None) -> MultiMutationResult:
305
"""
306
Remove multiple documents.
307
308
Args:
309
keys (List[str]): List of document keys to remove
310
options (RemoveOptions, optional): Remove options
311
312
Returns:
313
MultiMutationResult: Results for each key
314
"""
315
```
316
317
## Operation Options
318
319
### Basic Operation Options
320
321
```python { .api }
322
class GetOptions:
323
def __init__(self, timeout: timedelta = None,
324
with_expiry: bool = False,
325
project: List[str] = None):
326
"""
327
Options for get operations.
328
329
Args:
330
timeout (timedelta, optional): Operation timeout
331
with_expiry (bool): Include expiration time in result
332
project (List[str], optional): Fields to project
333
"""
334
335
class UpsertOptions:
336
def __init__(self, timeout: timedelta = None,
337
expiry: timedelta = None,
338
durability: Durability = None,
339
cas: int = None):
340
"""
341
Options for upsert operations.
342
343
Args:
344
timeout (timedelta, optional): Operation timeout
345
expiry (timedelta, optional): Document expiration
346
durability (Durability, optional): Durability requirements
347
cas (int, optional): CAS value for optimistic locking
348
"""
349
350
class InsertOptions:
351
def __init__(self, timeout: timedelta = None,
352
expiry: timedelta = None,
353
durability: Durability = None):
354
"""
355
Options for insert operations.
356
357
Args:
358
timeout (timedelta, optional): Operation timeout
359
expiry (timedelta, optional): Document expiration
360
durability (Durability, optional): Durability requirements
361
"""
362
363
class ReplaceOptions:
364
def __init__(self, timeout: timedelta = None,
365
expiry: timedelta = None,
366
durability: Durability = None,
367
cas: int = None):
368
"""
369
Options for replace operations.
370
371
Args:
372
timeout (timedelta, optional): Operation timeout
373
expiry (timedelta, optional): Document expiration
374
durability (Durability, optional): Durability requirements
375
cas (int, optional): CAS value for optimistic locking
376
"""
377
378
class RemoveOptions:
379
def __init__(self, timeout: timedelta = None,
380
durability: Durability = None,
381
cas: int = None):
382
"""
383
Options for remove operations.
384
385
Args:
386
timeout (timedelta, optional): Operation timeout
387
durability (Durability, optional): Durability requirements
388
cas (int, optional): CAS value for optimistic locking
389
"""
390
```
391
392
### Counter Operation Options
393
394
```python { .api }
395
class IncrementOptions:
396
def __init__(self, timeout: timedelta = None,
397
expiry: timedelta = None,
398
durability: Durability = None,
399
delta: int = 1,
400
initial: int = None):
401
"""
402
Options for increment operations.
403
404
Args:
405
timeout (timedelta, optional): Operation timeout
406
expiry (timedelta, optional): Document expiration
407
durability (Durability, optional): Durability requirements
408
delta (int): Increment amount (default: 1)
409
initial (int, optional): Initial value if document doesn't exist
410
"""
411
412
class DecrementOptions:
413
def __init__(self, timeout: timedelta = None,
414
expiry: timedelta = None,
415
durability: Durability = None,
416
delta: int = 1,
417
initial: int = None):
418
"""
419
Options for decrement operations.
420
421
Args:
422
timeout (timedelta, optional): Operation timeout
423
expiry (timedelta, optional): Document expiration
424
durability (Durability, optional): Durability requirements
425
delta (int): Decrement amount (default: 1)
426
initial (int, optional): Initial value if document doesn't exist
427
"""
428
```
429
430
## Result Types
431
432
```python { .api }
433
class GetResult:
434
@property
435
def content_as(self) -> ContentProxy:
436
"""Access document content with type conversion."""
437
438
@property
439
def cas(self) -> int:
440
"""Document CAS value."""
441
442
@property
443
def expiry_time(self) -> datetime:
444
"""Document expiration time (if requested)."""
445
446
class MutationResult:
447
@property
448
def cas(self) -> int:
449
"""New CAS value after mutation."""
450
451
@property
452
def mutation_token(self) -> MutationToken:
453
"""Mutation token for consistency."""
454
455
class ExistsResult:
456
@property
457
def exists(self) -> bool:
458
"""Whether document exists."""
459
460
@property
461
def cas(self) -> int:
462
"""Document CAS value if exists."""
463
464
class CounterResult(MutationResult):
465
@property
466
def content(self) -> int:
467
"""New counter value."""
468
469
class GetReplicaResult:
470
@property
471
def content_as(self) -> ContentProxy:
472
"""Access document content with type conversion."""
473
474
@property
475
def cas(self) -> int:
476
"""Document CAS value."""
477
478
@property
479
def is_replica(self) -> bool:
480
"""True if document came from replica, False if from active."""
481
482
class MultiGetResult:
483
def __getitem__(self, key: str) -> GetResult:
484
"""Get result for specific key."""
485
486
def __iter__(self) -> Iterator[Tuple[str, GetResult]]:
487
"""Iterate over key-result pairs."""
488
489
def __len__(self) -> int:
490
"""Number of results."""
491
492
class MultiMutationResult:
493
def __getitem__(self, key: str) -> MutationResult:
494
"""Get mutation result for specific key."""
495
496
def __iter__(self) -> Iterator[Tuple[str, MutationResult]]:
497
"""Iterate over key-result pairs."""
498
499
def __len__(self) -> int:
500
"""Number of results."""
501
502
class ContentProxy:
503
def __getitem__(self, key: type):
504
"""Get content as specific type (dict, list, str, etc.)."""
505
```
506
507
## Usage Examples
508
509
### Basic Operations
510
511
```python
512
from datetime import timedelta
513
514
# Basic get/upsert
515
doc = {"name": "John", "age": 30}
516
result = collection.upsert("user::123", doc)
517
print(f"CAS: {result.cas}")
518
519
get_result = collection.get("user::123")
520
print(f"Name: {get_result.content_as[dict]['name']}")
521
522
# With expiration
523
collection.upsert("temp::data", {"value": 42},
524
UpsertOptions(expiry=timedelta(hours=1)))
525
526
# Conditional replace
527
try:
528
collection.replace("user::123", {"name": "Jane", "age": 25},
529
ReplaceOptions(cas=get_result.cas))
530
except CASMismatchException:
531
print("Document was modified by another process")
532
```
533
534
### Counter Operations
535
536
```python
537
# Initialize counter
538
collection.binary().increment("counter::page_views",
539
IncrementOptions(initial=0))
540
541
# Increment by 5
542
result = collection.binary().increment("counter::page_views",
543
IncrementOptions(delta=5))
544
print(f"New value: {result.content}")
545
```
546
547
### Multi-Document Operations
548
549
```python
550
# Batch get
551
keys = ["user::1", "user::2", "user::3"]
552
results = collection.get_multi(keys)
553
for key, result in results.results.items():
554
if result.success:
555
print(f"{key}: {result.content_as[dict]}")
556
557
# Batch upsert
558
docs = {
559
"user::100": {"name": "Alice", "age": 28},
560
"user::101": {"name": "Bob", "age": 35}
561
}
562
collection.upsert_multi(docs)
563
```