In MongoDB’s pymongo, how do I do a count()?

Since pymongo version 3.7.0 and above count() is deprecated. Instead use Collection.count_documents. Running cursor.count or collection.count will result in following warning message: DeprecationWarning: count is deprecated. Use Collection.count_documents instead. To use count_documents the code can be adjusted as follows import pymongo db = pymongo.MongoClient() col = db[DATABASE][COLLECTION] find = {“test_set”:”abc”} sort = [(“abc”,pymongo.DESCENDING)] skip = …

Read more

MongoDB: count the number of items in an array

In MongoDB 2.6, the Aggregation Framework has a new array $size operator you can use: > db.mycollection.insert({‘foo’:[1,2,3,4]}) > db.mycollection.insert({‘foo’:[5,6,7]}) > db.mycollection.aggregate([{$project: { count: { $size:”$foo” }}}]) { “_id” : ObjectId(“5314b5c360477752b449eedf”), “count” : 4 } { “_id” : ObjectId(“5314b5c860477752b449eee0”), “count” : 3 }

Checking if an Index exists in mongodb

Creating indexes in MongoDB is an idempotent operation. So running db.names.createIndex({name:1}) would create the index only if it didn’t already exist. The deprecated (as of MongoDB 3.0) alias for createIndex() is ensureIndex() which is a bit clearer on what createIndex() actually does. Edit: Thanks to ZitRo for clarifying in comments that calling createIndex() with the …

Read more

Cascade style delete in Mongoose

This is one of the primary use cases of Mongoose’s ‘remove’ middleware. clientSchema.pre(‘remove’, function(next) { // ‘this’ is the client being removed. Provide callbacks here if you want // to be notified of the calls’ result. Sweepstakes.remove({client_id: this._id}).exec(); Submission.remove({client_id: this._id}).exec(); next(); }); This way, when you call client.remove() this middleware is automatically invoked to clean …

Read more