or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregation.mdclient.mdcollection-crud.mdconfiguration.mdcursors.mddatabase.mderrors.mdindex.mdindexing.mdtesting-utilities.md

database.mddocs/

0

# Database Operations

1

2

Database-level operations including collection management, database commands, and configuration. The Database class provides the interface for working with MongoDB databases in mongomock.

3

4

## Capabilities

5

6

### Collection Access

7

8

Access collections within the database with support for configuration options and dynamic collection creation.

9

10

```python { .api }

11

def get_collection(self, name, codec_options=None, read_preference=None,

12

write_concern=None, read_concern=None):

13

"""

14

Get a collection instance.

15

16

Parameters:

17

- name: str, collection name

18

- codec_options: CodecOptions, encoding/decoding options

19

- read_preference: ReadPreference, read preference override

20

- write_concern: WriteConcern, write concern override

21

- read_concern: ReadConcern, read concern override

22

23

Returns:

24

Collection instance

25

"""

26

```

27

28

**Usage Example:**

29

30

```python

31

client = mongomock.MongoClient()

32

db = client.testdb

33

34

# Get collection by name

35

collection = db.get_collection('users')

36

collection = db['users'] # Alternative syntax

37

collection = db.users # Alternative syntax

38

39

# Get collection with custom options

40

from mongomock import WriteConcern, CodecOptions

41

collection = db.get_collection('users',

42

write_concern=WriteConcern(w=1),

43

codec_options=CodecOptions(tz_aware=True)

44

)

45

```

46

47

### Collection Management

48

49

Create, list, drop, and rename collections within the database.

50

51

```python { .api }

52

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

53

"""

54

List all collection names in the database.

55

56

Parameters:

57

- filter: dict, filter criteria for collections

58

- session: ClientSession, session to use (ignored)

59

60

Returns:

61

List[str]: list of collection names

62

"""

63

64

def list_collections(self, filter=None, session=None, nameOnly=False):

65

"""

66

List collections in the database with full metadata.

67

68

Parameters:

69

- filter: dict, filter criteria for collections

70

- session: ClientSession, session to use (ignored)

71

- nameOnly: bool, return names only if True

72

73

Returns:

74

CommandCursor: cursor over collection information documents

75

"""

76

77

def collection_names(self, include_system_collections=True, session=None):

78

"""

79

Get collection names (deprecated, use list_collection_names).

80

81

Parameters:

82

- include_system_collections: bool, include system collections

83

- session: ClientSession, session to use (ignored)

84

85

Returns:

86

List[str]: list of collection names

87

88

Deprecated:

89

Use list_collection_names() instead

90

"""

91

92

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

93

"""

94

Create a new collection.

95

96

Parameters:

97

- name: str, collection name

98

- **kwargs: collection creation options

99

100

Returns:

101

Collection instance

102

103

Raises:

104

CollectionInvalid: if collection already exists or invalid name

105

"""

106

107

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

108

"""

109

Drop a collection from the database.

110

111

Parameters:

112

- name_or_collection: str or Collection, collection name or instance

113

- session: ClientSession, session to use (ignored)

114

115

Returns:

116

None

117

"""

118

119

def rename_collection(self, name, new_name, dropTarget=False):

120

"""

121

Rename a collection.

122

123

Parameters:

124

- name: str, current collection name

125

- new_name: str, new collection name

126

- dropTarget: bool, drop target collection if exists

127

128

Returns:

129

None

130

131

Raises:

132

OperationFailure: if operation fails

133

"""

134

```

135

136

**Usage Example:**

137

138

```python

139

db = mongomock.MongoClient().testdb

140

141

# List collections

142

collections = db.list_collection_names()

143

print(f"Collections: {collections}")

144

145

# Create collection explicitly

146

users_col = db.create_collection('users')

147

148

# Drop collection

149

db.drop_collection('users')

150

# or

151

db.drop_collection(users_col)

152

153

# Rename collection

154

db.create_collection('old_name')

155

db.rename_collection('old_name', 'new_name')

156

```

157

158

### Database Commands

159

160

Execute database-level commands and administrative operations.

161

162

```python { .api }

163

def command(self, command, **kwargs):

164

"""

165

Execute a database command.

166

167

Parameters:

168

- command: str or dict, command to execute

169

- **kwargs: additional command parameters

170

171

Returns:

172

Dict[str, Any]: command result

173

174

Raises:

175

OperationFailure: if command fails

176

"""

177

```

178

179

**Usage Example:**

180

181

```python

182

db = mongomock.MongoClient().testdb

183

184

# Execute database commands

185

result = db.command('dbStats')

186

result = db.command({'collStats': 'users'})

187

188

# List collections via command

189

result = db.command('listCollections')

190

```

191

192

### DBRef Dereferencing

193

194

Resolve database references to actual documents.

195

196

```python { .api }

197

def dereference(self, dbref, session=None):

198

"""

199

Dereference a DBRef to get the referenced document.

200

201

Parameters:

202

- dbref: DBRef, database reference to resolve

203

- session: ClientSession, session to use (ignored)

204

205

Returns:

206

Dict[str, Any] or None: referenced document or None if not found

207

"""

208

```

209

210

**Usage Example:**

211

212

```python

213

from bson import DBRef, ObjectId

214

215

db = mongomock.MongoClient().testdb

216

217

# Create a reference

218

ref = DBRef('users', ObjectId())

219

220

# Dereference

221

document = db.dereference(ref)

222

```

223

224

### Database Configuration

225

226

Create database instances with different configuration options.

227

228

```python { .api }

229

def with_options(self, codec_options=None, read_preference=None,

230

write_concern=None, read_concern=None):

231

"""

232

Create a new Database instance with different options.

233

234

Parameters:

235

- codec_options: CodecOptions, encoding/decoding options

236

- read_preference: ReadPreference, read preference setting

237

- write_concern: WriteConcern, write concern setting

238

- read_concern: ReadConcern, read concern setting

239

240

Returns:

241

Database: new database instance with updated options

242

"""

243

```

244

245

**Usage Example:**

246

247

```python

248

from mongomock import WriteConcern, ReadConcern, CodecOptions

249

250

db = mongomock.MongoClient().testdb

251

252

# Create database with custom options

253

custom_db = db.with_options(

254

write_concern=WriteConcern(w=1),

255

read_concern=ReadConcern(level='majority'),

256

codec_options=CodecOptions(tz_aware=True)

257

)

258

```

259

260

### Database Properties

261

262

Access database configuration and metadata.

263

264

```python { .api }

265

@property

266

def name(self):

267

"""str: database name"""

268

269

@property

270

def client(self):

271

"""MongoClient: client instance that created this database"""

272

273

@property

274

def read_preference(self):

275

"""ReadPreference: current read preference"""

276

277

@property

278

def codec_options(self):

279

"""CodecOptions: current codec options"""

280

281

@property

282

def read_concern(self):

283

"""ReadConcern: current read concern"""

284

```

285

286

**Usage Example:**

287

288

```python

289

client = mongomock.MongoClient()

290

db = client.testdb

291

292

print(f"Database name: {db.name}")

293

print(f"Client: {db.client}")

294

print(f"Read preference: {db.read_preference}")

295

print(f"Codec options: {db.codec_options}")

296

```

297

298

## Database Constructor

299

300

```python { .api }

301

class Database:

302

def __init__(self, client, name, _store, read_preference=None,

303

codec_options=None, read_concern=None):

304

"""

305

Create a Database instance.

306

307

Note: Databases are typically created via MongoClient.get_database()

308

rather than direct instantiation.

309

310

Parameters:

311

- client: MongoClient, parent client instance

312

- name: str, database name

313

- _store: Store, internal storage backend

314

- read_preference: ReadPreference, read preference setting

315

- codec_options: CodecOptions, codec options

316

- read_concern: ReadConcern, read concern setting

317

"""

318

```