or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-queries.mdbson-handling.mdbulk-transactions.mdclient-connection.mddatabase-collection.mdgridfs-storage.mdindex.mdmonitoring-events.md

database-collection.mddocs/

0

# Database and Collection Operations

1

2

Database management, collection operations, document CRUD operations, indexing, and basic query functionality.

3

4

## Capabilities

5

6

### Database Operations

7

8

Access and manage databases within a MongoDB deployment.

9

10

```python { .api }

11

class Database:

12

def __init__(self, client, name, **kwargs):

13

"""

14

Database instance for operations.

15

16

Parameters:

17

- client: MongoClient instance

18

- name: database name

19

- codec_options: BSON codec options

20

- read_preference: read preference

21

- write_concern: write concern

22

- read_concern: read concern

23

"""

24

25

def get_collection(self, name, **kwargs):

26

"""

27

Get a collection instance.

28

29

Parameters:

30

- name: collection name

31

- codec_options: BSON codec options

32

- read_preference: read preference

33

- write_concern: write concern

34

- read_concern: read concern

35

36

Returns:

37

Collection instance

38

"""

39

40

def list_collection_names(self, session=None, filter=None, **kwargs):

41

"""

42

List collection names in the database.

43

44

Parameters:

45

- session: optional ClientSession

46

- filter: optional filter criteria

47

48

Returns:

49

List of collection names

50

"""

51

52

def list_collections(self, session=None, filter=None, **kwargs):

53

"""

54

List collections with metadata.

55

56

Parameters:

57

- session: optional ClientSession

58

- filter: optional filter criteria

59

60

Returns:

61

CommandCursor with collection information

62

"""

63

64

def create_collection(self, name, **kwargs):

65

"""

66

Create a collection.

67

68

Parameters:

69

- name: collection name

70

- capped: create capped collection

71

- size: maximum size in bytes (capped collections)

72

- max: maximum number of documents (capped collections)

73

- validator: document validation rules

74

- validationLevel: validation strictness

75

- validationAction: action on validation failure

76

- session: optional ClientSession

77

78

Returns:

79

Collection instance

80

"""

81

82

def drop_collection(self, name_or_collection, session=None):

83

"""

84

Drop a collection.

85

86

Parameters:

87

- name_or_collection: collection name or Collection instance

88

- session: optional ClientSession

89

"""

90

91

@property

92

def client(self):

93

"""

94

MongoClient instance for this database.

95

96

Returns:

97

MongoClient instance

98

"""

99

100

@property

101

def name(self):

102

"""

103

Database name.

104

105

Returns:

106

str: Database name

107

"""

108

```

109

110

### Collection CRUD Operations

111

112

Core document operations for creating, reading, updating, and deleting documents.

113

114

```python { .api }

115

class Collection:

116

def insert_one(self, document, bypass_document_validation=False, session=None):

117

"""

118

Insert a single document.

119

120

Parameters:

121

- document: document to insert

122

- bypass_document_validation: skip validation

123

- session: optional ClientSession

124

125

Returns:

126

InsertOneResult with inserted_id

127

"""

128

129

def insert_many(

130

self,

131

documents,

132

ordered=True,

133

bypass_document_validation=False,

134

session=None

135

):

136

"""

137

Insert multiple documents.

138

139

Parameters:

140

- documents: sequence of documents

141

- ordered: stop on first error if True

142

- bypass_document_validation: skip validation

143

- session: optional ClientSession

144

145

Returns:

146

InsertManyResult with inserted_ids

147

"""

148

149

def find_one(self, filter=None, *args, **kwargs):

150

"""

151

Find a single document.

152

153

Parameters:

154

- filter: query criteria

155

- projection: fields to return

156

- skip: number of documents to skip

157

- sort: sort specification

158

- max_time_ms: maximum execution time

159

- session: optional ClientSession

160

161

Returns:

162

Document or None

163

"""

164

165

def find(self, filter=None, projection=None, skip=0, limit=0, **kwargs):

166

"""

167

Find documents matching criteria.

168

169

Parameters:

170

- filter: query criteria

171

- projection: fields to return

172

- skip: number of documents to skip

173

- limit: maximum number of documents

174

- sort: sort specification

175

- batch_size: cursor batch size

176

- max_time_ms: maximum execution time

177

- session: optional ClientSession

178

179

Returns:

180

Cursor instance

181

"""

182

183

def update_one(

184

self,

185

filter,

186

update,

187

upsert=False,

188

bypass_document_validation=False,

189

session=None,

190

**kwargs

191

):

192

"""

193

Update a single document.

194

195

Parameters:

196

- filter: query criteria

197

- update: update specification

198

- upsert: insert if no match found

199

- bypass_document_validation: skip validation

200

- session: optional ClientSession

201

202

Returns:

203

UpdateResult

204

"""

205

206

def update_many(

207

self,

208

filter,

209

update,

210

upsert=False,

211

bypass_document_validation=False,

212

session=None,

213

**kwargs

214

):

215

"""

216

Update multiple documents.

217

218

Parameters:

219

- filter: query criteria

220

- update: update specification

221

- upsert: insert if no match found

222

- bypass_document_validation: skip validation

223

- session: optional ClientSession

224

225

Returns:

226

UpdateResult

227

"""

228

229

def replace_one(

230

self,

231

filter,

232

replacement,

233

upsert=False,

234

bypass_document_validation=False,

235

session=None,

236

**kwargs

237

):

238

"""

239

Replace a single document.

240

241

Parameters:

242

- filter: query criteria

243

- replacement: replacement document

244

- upsert: insert if no match found

245

- bypass_document_validation: skip validation

246

- session: optional ClientSession

247

248

Returns:

249

UpdateResult

250

"""

251

252

def delete_one(self, filter, session=None, **kwargs):

253

"""

254

Delete a single document.

255

256

Parameters:

257

- filter: query criteria

258

- session: optional ClientSession

259

260

Returns:

261

DeleteResult with deleted_count

262

"""

263

264

def delete_many(self, filter, session=None, **kwargs):

265

"""

266

Delete multiple documents.

267

268

Parameters:

269

- filter: query criteria

270

- session: optional ClientSession

271

272

Returns:

273

DeleteResult with deleted_count

274

"""

275

276

def count_documents(self, filter, session=None, **kwargs):

277

"""

278

Count documents matching criteria.

279

280

Parameters:

281

- filter: query criteria

282

- skip: number of documents to skip

283

- limit: maximum number to count

284

- max_time_ms: maximum execution time

285

- session: optional ClientSession

286

287

Returns:

288

int: Document count

289

"""

290

291

def estimated_document_count(self, **kwargs):

292

"""

293

Estimate total document count.

294

295

Parameters:

296

- max_time_ms: maximum execution time

297

298

Returns:

299

int: Estimated document count

300

"""

301

302

def distinct(self, key, filter=None, session=None, **kwargs):

303

"""

304

Get distinct values for a field.

305

306

Parameters:

307

- key: field name

308

- filter: query criteria

309

- max_time_ms: maximum execution time

310

- session: optional ClientSession

311

312

Returns:

313

List of distinct values

314

"""

315

```

316

317

### Find and Modify Operations

318

319

Atomic find-and-modify operations that return documents while modifying them.

320

321

```python { .api }

322

class Collection:

323

def find_one_and_delete(self, filter, projection=None, sort=None, session=None, **kwargs):

324

"""

325

Find and delete a document atomically.

326

327

Parameters:

328

- filter: query criteria

329

- projection: fields to return

330

- sort: sort specification

331

- max_time_ms: maximum execution time

332

- session: optional ClientSession

333

334

Returns:

335

Deleted document or None

336

"""

337

338

def find_one_and_replace(

339

self,

340

filter,

341

replacement,

342

projection=None,

343

sort=None,

344

upsert=False,

345

return_document=ReturnDocument.BEFORE,

346

session=None,

347

**kwargs

348

):

349

"""

350

Find and replace a document atomically.

351

352

Parameters:

353

- filter: query criteria

354

- replacement: replacement document

355

- projection: fields to return

356

- sort: sort specification

357

- upsert: insert if no match found

358

- return_document: return original or modified document

359

- bypass_document_validation: skip validation

360

- max_time_ms: maximum execution time

361

- session: optional ClientSession

362

363

Returns:

364

Original or modified document

365

"""

366

367

def find_one_and_update(

368

self,

369

filter,

370

update,

371

projection=None,

372

sort=None,

373

upsert=False,

374

return_document=ReturnDocument.BEFORE,

375

session=None,

376

**kwargs

377

):

378

"""

379

Find and update a document atomically.

380

381

Parameters:

382

- filter: query criteria

383

- update: update specification

384

- projection: fields to return

385

- sort: sort specification

386

- upsert: insert if no match found

387

- return_document: return original or modified document

388

- bypass_document_validation: skip validation

389

- max_time_ms: maximum execution time

390

- session: optional ClientSession

391

392

Returns:

393

Original or modified document

394

"""

395

```

396

397

### Cursor Operations

398

399

Navigate and process query results with cursors.

400

401

```python { .api }

402

class Cursor:

403

def __iter__(self):

404

"""Return cursor iterator."""

405

406

def __next__(self):

407

"""Get next document."""

408

409

def next(self):

410

"""Get next document (Python 2 compatibility)."""

411

412

def limit(self, limit):

413

"""

414

Limit number of results.

415

416

Parameters:

417

- limit: maximum number of documents

418

419

Returns:

420

Cursor instance (chainable)

421

"""

422

423

def skip(self, skip):

424

"""

425

Skip number of documents.

426

427

Parameters:

428

- skip: number of documents to skip

429

430

Returns:

431

Cursor instance (chainable)

432

"""

433

434

def sort(self, key_or_list, direction=1):

435

"""

436

Sort results.

437

438

Parameters:

439

- key_or_list: field name or list of (key, direction) pairs

440

- direction: 1 for ascending, -1 for descending

441

442

Returns:

443

Cursor instance (chainable)

444

"""

445

446

def batch_size(self, batch_size):

447

"""

448

Set cursor batch size.

449

450

Parameters:

451

- batch_size: number of documents per batch

452

453

Returns:

454

Cursor instance (chainable)

455

"""

456

457

def close(self):

458

"""Close the cursor."""

459

460

@property

461

def alive(self):

462

"""

463

Check if cursor is still alive.

464

465

Returns:

466

bool: True if cursor has more results

467

"""

468

469

def count(self, with_limit_and_skip=False):

470

"""

471

Count documents (deprecated - use count_documents).

472

473

Parameters:

474

- with_limit_and_skip: apply limit/skip to count

475

476

Returns:

477

int: Document count

478

"""

479

```

480

481

## Usage Examples

482

483

### Basic CRUD Operations

484

485

```python

486

from pymongo import MongoClient

487

488

client = MongoClient()

489

db = client.mydb

490

collection = db.mycollection

491

492

# Insert documents

493

doc = {"name": "Alice", "age": 30}

494

result = collection.insert_one(doc)

495

print(f"Inserted: {result.inserted_id}")

496

497

docs = [

498

{"name": "Bob", "age": 25},

499

{"name": "Charlie", "age": 35}

500

]

501

result = collection.insert_many(docs)

502

print(f"Inserted: {result.inserted_ids}")

503

504

# Find documents

505

doc = collection.find_one({"name": "Alice"})

506

print(f"Found: {doc}")

507

508

for doc in collection.find({"age": {"$gte": 30}}):

509

print(f"Adult: {doc}")

510

511

# Update documents

512

result = collection.update_one(

513

{"name": "Alice"},

514

{"$set": {"age": 31}}

515

)

516

print(f"Modified: {result.modified_count}")

517

518

# Delete documents

519

result = collection.delete_one({"name": "Alice"})

520

print(f"Deleted: {result.deleted_count}")

521

```

522

523

### Working with Cursors

524

525

```python

526

from pymongo import ASCENDING, DESCENDING

527

528

# Query with cursor operations

529

cursor = collection.find({"age": {"$lt": 50}}) \

530

.sort([("age", ASCENDING), ("name", DESCENDING)]) \

531

.skip(10) \

532

.limit(5)

533

534

for doc in cursor:

535

print(doc)

536

537

# Get distinct values

538

ages = collection.distinct("age")

539

print(f"Distinct ages: {ages}")

540

```

541

542

### Find and Modify

543

544

```python

545

from pymongo import ReturnDocument

546

547

# Find and update atomically

548

updated_doc = collection.find_one_and_update(

549

{"name": "Alice"},

550

{"$inc": {"age": 1}},

551

return_document=ReturnDocument.AFTER

552

)

553

print(f"Updated document: {updated_doc}")

554

555

# Find and delete atomically

556

deleted_doc = collection.find_one_and_delete({"name": "Bob"})

557

print(f"Deleted document: {deleted_doc}")

558

```