Export and Import Mongodb commands

To restore earlier database

mongorestore -d dbname -c users C:/mypath/to/old/dbname

To export a collection

mongoexport --db envyd --collection categories --out users_remote.json

To import a collection

mongoimport --db envyd --collection posts --file posts.json

To Update Single or Multiple records

Update single 
    db.users.update({}, {$set:{"email":'new_email_here'}})

Update multiple
    db.users.updateMany({}, {$set: {email: 'new_email_here'}})

To Query a collection for an array type field, by the length or array comparison

{ $where: "if (this.media && this.media.length > 1) {return this; } "}

Query with multiple fields is as simple as writing general javascript condition

{ $where: "if (this.media && this.media.length > 1 && this.status=='Published') {return this; } "}

To Query by doing comparison on ObjectId type field

By doing toString comparison

    { $where: "if (this.media && this.media.length > 1 && this.status=='Published' && 
    this.userId.toString() != this.createdBy.toString()) {return this; } "}

By using equals method
    {$where: "if(this.media && this.media.length > 1 && this.status=='Published' && 
    !this.userId.equals(this.createdBy)) {return this;}"}

Leave a Reply