Push items into mongo array via mongoose

Assuming, var friend = { firstName: ‘Harry’, lastName: ‘Potter’ }; There are two options you have: Update the model in-memory, and save (plain javascript array.push): person.friends.push(friend); person.save(done); or PersonModel.update( { _id: person._id }, { $push: { friends: friend } }, done ); I always try and go for the first option when possible, because it’ll … Read more

How do I manage MongoDB connections in a Node.js web application?

The primary committer to node-mongodb-native says: You open do MongoClient.connect once when your app boots up and reuse the db object. It’s not a singleton connection pool each .connect creates a new connection pool. So, to answer your question directly, reuse the db object that results from MongoClient.connect(). This gives you pooling, and will provide … Read more

Random record from MongoDB

Starting with the 3.2 release of MongoDB, you can get N random docs from a collection using the $sample aggregation pipeline operator: // Get one random document from the mycoll collection. db.mycoll.aggregate([{ $sample: { size: 1 } }]) If you want to select the random document(s) from a filtered subset of the collection, prepend a … Read more

How to filter array in subdocument with MongoDB [duplicate]

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together: db.test.aggregate([ { $match: {_id: ObjectId(“512e28984815cbfcb21646a7”)}}, { $unwind: ‘$list’}, { $match: {‘list.a’: {$gt: 3}}}, { $group: {_id: ‘$_id’, list: {$push: ‘$list.a’}}} ]) … Read more

Get names of all keys in the collection

You could do this with MapReduce: mr = db.runCommand({ “mapreduce” : “my_collection”, “map” : function() { for (var key in this) { emit(key, null); } }, “reduce” : function(key, stuff) { return null; }, “out”: “my_collection” + “_keys” }) Then run distinct on the resulting collection so as to find all the keys: db[mr.result].distinct(“_id”) [“foo”, … Read more

Group result by 15 minutes time interval in MongoDb

There are a couple of ways to do this. The first is with Date Aggregation Operators, which allow you to dissect the “date” values in documents. Specifically for “grouping” as the primary intent: db.collection.aggregate([ { “$group”: { “_id”: { “year”: { “$year”: “$created_at” }, “dayOfYear”: { “$dayOfYear”: “$created_at” }, “hour”: { “$hour”: “$created_at” }, “interval”: … Read more

Querying after populate in Mongoose

With a modern MongoDB greater than 3.2 you can use $lookup as an alternate to .populate() in most cases. This also has the advantage of actually doing the join “on the server” as opposed to what .populate() does which is actually “multiple queries” to “emulate” a join. So .populate() is not really a “join” in … Read more