Rock Mountain
  • Home
  • User Guide
    • Glass Web Components
    • Using reCAPTCHA
    • Publishing Source Code with Syntax Highlighting
  • Developer Guide
    • Getting Started
    • Adding NPM Packages
    • Database
      • Backing Up and Restoring Data
      • Database Schema
      • MongoDB Tips and Snippets
      • VS Code and the MongoDB Playground
    • Common Errors and Their Solutions
    • Developing Glass Web Components
    • DevOps
      • Build and Deployment Procedure
      • GitHub Conventions and Workflow
      • Merging Preview Into Main
    • File Structure
    • React Components
      • SiteLayout Component
      • Toggle Lazy Load Image Component
    • Update or Change the Fav Icon
    • References and Learning Resources
  • Icons
Powered by GitBook
On this page
  • Rename a field
  • Add a new field
  • Find Documents Missing a Given Field
  • Remove a Field
  • Delete a Document
  1. Developer Guide
  2. Database

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

db.documents.update(
    {},
    {$set : {"location":"/blog"}},
    {upsert:false,
    multi:true}
) 
  • 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 } }

or

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

Remove a Field

db.documents.update(
    {},
    {$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"} )
PreviousDatabase SchemaNextVS Code and the MongoDB Playground

Last updated 3 years ago