Link Search Menu Expand Document

MongoDB Tips and Snippets

A sort of “cheat-sheet” full of useful tips and snippets…

Rename a field

jsdb.collectionName.updateMany({}, {$rename: {'StudentName': "StudentFirstName"}});

Add a new field

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

    {$set : {"location":"/blog"}},
  • Upsert: If set to true, creates a new document when no document matches the query criteria.
  • Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

No value:

db.your_collection.update({}, {$set : {"new_field":null}}, {upsert:false, multi:true})

Empty array:

db.your_collection.update({}, {$set : {"new_field":[]}}, {upsert:false, multi:true})

Find Documents Missing a Given Field

{ created : { $exists : false } }


db.documents.find( { created : { $exists : false } } )

Remove a Field

    {$unset: {"location":1}},
    {upsert:false, multi:true}

Delete a Document

Typically, you’d want to delete only by the document’s unique _id, but it can also be done in the same way by some other known field value:

db.documents.deleteOne( { title: "Renew Your SSL Certificate"} )