How do I perform the SQL Join equivalent in MongoDB?

As of Mongo 3.2 the answers to this question are mostly no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join: https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup From the docs: { $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the … Read more

Update MongoDB field using value of another field

The best way to do this is in version 4.2+ which allows using of aggregation pipeline in the update document and the updateOne, updateMany or update collection methods. Note that the latter has been deprecated in most if not all languages drivers. MongoDB 4.2+ Version 4.2 also introduced the $set pipeline stage operator which is … Read more

Retrieve only the queried element in an object array in MongoDB collection

MongoDB 2.2’s new $elemMatch projection operator provides another way to alter the returned document to contain only the first matched shapes element: db.test.find( {“shapes.color”: “red”}, {_id: 0, shapes: {$elemMatch: {color: “red”}}}); Returns: {“shapes” : [{“shape”: “circle”, “color”: “red”}]} In 2.2 you can also do this using the $ projection operator, where the $ in a … Read more

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

tech