How to remove array element in mongodb?

Try the following query: collection.update( { _id: id }, { $pull: { ‘contact.phone’: { number: ‘+1786543589455’ } } } ); It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array. You can use $unset to unset the value in the array (set it to null), but not to … Read more

Mongodb $push in nested array

Probably something like this where ID is your ObjectId. The first {} are necessary to identify your document. It is not required to use an ObjectId as long as you have another unique identifier in your collection. db.collection.update( { “_id”: ID, “playlists._id”: “58”}, { “$push”: {“playlists.$.musics”: { “name”: “test name”, “duration”: “4.00” } } } … Read more

How to properly reuse connection to Mongodb across NodeJs application and modules

You can create a mongoUtil.js module that has functions to both connect to mongo and return a mongo db instance: const MongoClient = require( ‘mongodb’ ).MongoClient; const url = “mongodb://localhost:27017”; var _db; module.exports = { connectToServer: function( callback ) { MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) { _db = client.db(‘test_db’); return … Read more

MongoDB: Combine data from multiple collections into one..how?

MongoDB 3.2 now allows one to combine data from multiple collections into one through the $lookup aggregation stage. As a practical example, lets say that you have data about books split into two different collections. First collection, called books, having the following data: { “isbn”: “978-3-16-148410-0”, “title”: “Some cool book”, “author”: “John Doe” } { … Read more

Find document with array that contains a specific value

As favouriteFoods is a simple array of strings, you can just query that field directly: PersonModel.find({ favouriteFoods: “sushi” }, …); // favouriteFoods contains “sushi” But I’d also recommend making the string array explicit in your schema: person = { name : String, favouriteFoods : [String] } The relevant documentation can be found here: https://docs.mongodb.com/manual/tutorial/query-arrays/