or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin-operations.mdcollection-operations.mddatabase-connection.mdgridfs-storage.mdindex.mdquery-cursor.mdutilities-helpers.md

collection-operations.mddocs/

0

# Collection Operations

1

2

Enhanced collection interface with convenience methods for common database operations, including findById, updateById, and removeById.

3

4

## Capabilities

5

6

### Basic Collection Methods

7

8

Standard MongoDB collection operations with enhanced connection handling.

9

10

```javascript { .api }

11

/**

12

* Insert documents into collection

13

* @param {object|object[]} docs - Document(s) to insert

14

* @param {object} [options] - Insert options

15

* @param {function} [callback] - Callback function (err, result)

16

* @returns {SkinCollection} this

17

*/

18

insert(docs, options, callback);

19

20

/**

21

* Update documents in collection

22

* @param {object} query - Query selector

23

* @param {object} update - Update operations

24

* @param {object} [options] - Update options

25

* @param {function} [callback] - Callback function (err, result)

26

* @returns {SkinCollection} this

27

*/

28

update(query, update, options, callback);

29

30

/**

31

* Remove documents from collection

32

* @param {object} query - Query selector

33

* @param {object} [options] - Remove options

34

* @param {function} [callback] - Callback function (err, result)

35

* @returns {SkinCollection} this

36

*/

37

remove(query, options, callback);

38

39

/**

40

* Find a single document

41

* @param {object} query - Query selector

42

* @param {object} [options] - Query options

43

* @param {function} [callback] - Callback function (err, doc)

44

* @returns {SkinCollection} this

45

*/

46

findOne(query, options, callback);

47

```

48

49

### Enhanced Find Methods

50

51

Mongoskin provides several enhanced find methods for common query patterns.

52

53

```javascript { .api }

54

/**

55

* Find documents and return cursor or call callback

56

* @param {object} [query] - Query selector

57

* @param {object} [options] - Query options

58

* @param {function} [callback] - Callback function (err, cursor)

59

* @returns {SkinCursor|SkinCollection} cursor if no callback, otherwise this

60

*/

61

find(query, options, callback);

62

63

/**

64

* Find documents and return array directly

65

* @param {object} [query] - Query selector

66

* @param {object} [options] - Query options

67

* @param {function} callback - Callback function (err, items)

68

* @returns {SkinCollection} this

69

*/

70

findItems(query, options, callback);

71

72

/**

73

* Find documents and iterate with each callback

74

* @param {object} [query] - Query selector

75

* @param {object} [options] - Query options

76

* @param {function} eachCallback - Callback for each document (err, item)

77

* @returns {SkinCollection} this

78

*/

79

findEach(query, options, eachCallback);

80

```

81

82

**Usage Examples:**

83

84

```javascript

85

const mongoskin = require('mongoskin');

86

const db = mongoskin.db('mongodb://localhost:27017/myapp');

87

const users = db.collection('users');

88

89

// Standard find with cursor

90

users.find({ active: true }, (err, cursor) => {

91

if (err) throw err;

92

cursor.toArray((err, docs) => {

93

console.log('Found users:', docs);

94

});

95

});

96

97

// Find and get array directly

98

users.findItems({ role: 'admin' }, (err, admins) => {

99

if (err) throw err;

100

console.log('Admin users:', admins);

101

});

102

103

// Find and iterate each document

104

users.findEach({ age: { $gt: 18 } }, (err, user) => {

105

if (err) throw err;

106

if (user) {

107

console.log('Adult user:', user.name);

108

} else {

109

console.log('No more users');

110

}

111

});

112

```

113

114

### ID-based Operations

115

116

Convenient methods for operations using document _id.

117

118

```javascript { .api }

119

/**

120

* Find document by _id

121

* @param {string|ObjectID|number} id - Document _id

122

* @param {function} callback - Callback function (err, doc)

123

* @returns {SkinCollection} this

124

*/

125

findById(id, callback);

126

127

/**

128

* Update document by _id

129

* @param {string|ObjectID|number} id - Document _id

130

* @param {object} doc - Update operations

131

* @param {function} [callback] - Callback function (err, result)

132

* @returns {SkinCollection} this

133

*/

134

updateById(id, doc, callback);

135

136

/**

137

* Remove document by _id

138

* @param {string|ObjectID|number} id - Document _id

139

* @param {function} [callback] - Callback function (err, result)

140

* @returns {SkinCollection} this

141

*/

142

removeById(id, callback);

143

```

144

145

**Usage Examples:**

146

147

```javascript

148

const mongoskin = require('mongoskin');

149

const db = mongoskin.db('mongodb://localhost:27017/myapp');

150

const users = db.collection('users');

151

152

// Find by ID (string, ObjectID, or number)

153

users.findById('507f1f77bcf86cd799439011', (err, user) => {

154

if (err) throw err;

155

console.log('Found user:', user);

156

});

157

158

// Update by ID

159

users.updateById('507f1f77bcf86cd799439011', { $set: { active: false } }, (err, result) => {

160

if (err) throw err;

161

console.log('Update result:', result);

162

});

163

164

// Remove by ID

165

users.removeById('507f1f77bcf86cd799439011', (err, result) => {

166

if (err) throw err;

167

console.log('Remove result:', result);

168

});

169

```

170

171

### Collection Extension

172

173

Bind custom methods to collection instances for reusable functionality.

174

175

```javascript { .api }

176

/**

177

* Bind custom methods or properties to collection

178

* @param {object} extendObject - Object with methods/properties to bind

179

* @returns {void}

180

*/

181

bind(extendObject);

182

```

183

184

**Usage Examples:**

185

186

```javascript

187

const mongoskin = require('mongoskin');

188

const db = mongoskin.db('mongodb://localhost:27017/myapp');

189

const users = db.collection('users');

190

191

// Bind custom methods

192

users.bind({

193

findByEmail: function(email, callback) {

194

this.findOne({ email: email }, callback);

195

},

196

197

findActiveUsers: function(callback) {

198

this.findItems({ active: true }, callback);

199

},

200

201

getUserStats: function(callback) {

202

this.aggregate([

203

{ $group: { _id: '$role', count: { $sum: 1 } } }

204

], callback);

205

}

206

});

207

208

// Use custom methods

209

users.findByEmail('user@example.com', (err, user) => {

210

if (err) throw err;

211

console.log('User by email:', user);

212

});

213

214

users.findActiveUsers((err, activeUsers) => {

215

if (err) throw err;

216

console.log('Active users:', activeUsers.length);

217

});

218

```

219

220

### Index Management

221

222

Collection index operations for performance optimization.

223

224

```javascript { .api }

225

/**

226

* Ensure index exists on collection

227

* @param {object} fieldOrSpec - Index specification

228

* @param {object} [options] - Index options

229

* @param {function} [callback] - Callback function (err, indexName)

230

* @returns {SkinCollection} this

231

*/

232

ensureIndex(fieldOrSpec, options, callback);

233

234

/**

235

* Create index on collection

236

* @param {object} fieldOrSpec - Index specification

237

* @param {object} [options] - Index options

238

* @param {function} [callback] - Callback function (err, indexName)

239

* @returns {SkinCollection} this

240

*/

241

createIndex(fieldOrSpec, options, callback);

242

243

/**

244

* Drop index from collection

245

* @param {string} indexName - Name of index to drop

246

* @param {function} [callback] - Callback function (err, result)

247

* @returns {SkinCollection} this

248

*/

249

dropIndex(indexName, callback);

250

251

/**

252

* List all indexes on collection

253

* @param {function} callback - Callback function (err, indexes)

254

* @returns {SkinCollection} this

255

*/

256

indexes(callback);

257

```

258

259

**Usage Examples:**

260

261

```javascript

262

const users = db.collection('users');

263

264

// Create single field index

265

users.ensureIndex({ email: 1 }, { unique: true }, (err, indexName) => {

266

if (err) throw err;

267

console.log('Created index:', indexName);

268

});

269

270

// Create compound index

271

users.createIndex({ name: 1, age: -1 }, (err, indexName) => {

272

if (err) throw err;

273

console.log('Created compound index:', indexName);

274

});

275

276

// List all indexes

277

users.indexes((err, indexes) => {

278

if (err) throw err;

279

console.log('Collection indexes:', indexes);

280

});

281

```

282

283

### Aggregation Operations

284

285

MongoDB aggregation pipeline operations.

286

287

```javascript { .api }

288

/**

289

* Perform aggregation operation

290

* @param {object[]} pipeline - Aggregation pipeline stages

291

* @param {object} [options] - Aggregation options

292

* @param {function} [callback] - Callback function (err, result)

293

* @returns {SkinCollection} this

294

*/

295

aggregate(pipeline, options, callback);

296

297

/**

298

* Perform map-reduce operation

299

* @param {function} map - Map function

300

* @param {function} reduce - Reduce function

301

* @param {object} [options] - MapReduce options

302

* @param {function} [callback] - Callback function (err, result)

303

* @returns {SkinCollection} this

304

*/

305

mapReduce(map, reduce, options, callback);

306

```

307

308

**Usage Examples:**

309

310

```javascript

311

const users = db.collection('users');

312

313

// Aggregation pipeline

314

users.aggregate([

315

{ $match: { active: true } },

316

{ $group: { _id: '$department', count: { $sum: 1 } } },

317

{ $sort: { count: -1 } }

318

], (err, result) => {

319

if (err) throw err;

320

console.log('Department stats:', result);

321

});

322

323

// Map-reduce operation

324

const map = function() { emit(this.department, 1); };

325

const reduce = function(key, values) { return values.length; };

326

327

users.mapReduce(map, reduce, { out: { inline: 1 } }, (err, result) => {

328

if (err) throw err;

329

console.log('Map-reduce result:', result);

330

});

331

```