Collection of
MongoDB tips and tricks
, want to add your tips? Checkout contributing.md
P.S: All these commands are tested on MongoDB shell version v3.4.2
.
- Import data into the collection using JSON generated By Mongoexport
- Import data into the collection using regular JSON
- Restore data into Atlas using dump
- Import data into Atlas using mongoimport
each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
- Insert a single document
- Insert multiple documents
- Inserts a document or documents into a collection
- Update a field to an empty array in all documents
- Insert a new field into a collection
- Find value inside array
- Find documents where field value is empty
- Find documents where field value is non empty
mongoimport --db <databaseName> --collection <collectionName> --drop --file <jsonFile>.json
mongoimport --db <databaseName> --collection <collectionName> --drop --file <jsonFile>.json --jsonArray
mongorestore --ssl --host atlas-host1:27017,atlas-host2:27017,atlas-host3:27017 -u usename -p mypassword dump
mongoimport --host atlas-host1:27017,atlas-host2:27017,atlas-host3:27017 --ssl -u username -p 'password' --authenticationDatabase admin --db <database> --collection <collection> --file <file.json>
show dbs
db.copyDatabase(fromdb, todb)
db.copyDatabase(fromdb, todb, fromhost, username, password, mechanism)
db.mycollection.insertOne(
{ bookName: "Indian History", price: 100, tags: ["History"], size: { h: 28, w: 35.5, uom: "cm" } }
)
db.mycollection.insertMany([
{ bookName: "Modern science", price: 500.34, tags: ["science"], size: { h: 28, w: 35.5, uom: "cm" } },
{ bookName: "Computer Design", price: 300, tags: ["computer"], size: { h: 28, w: 35.5, uom: "cm" } },
)]
db.mycollection.insert([
{ bookName: "Modern science", price: 500.34, tags: ["science"], size: { h: 28, w: 35.5, uom: "cm" } },
{ bookName: "Computer Design", price: 300, tags: ["computer"], size: { h: 28, w: 35.5, uom: "cm" } },
])
db.mycollection.insert(
{ bookName: "Indian History", price: 100, tags: ["History"], size: { h: 28, w: 35.5, uom: "cm" } }
)
db.mycollection.update(
{},
{$set : {fieldName:[]} }, {multi:true}
)
db.mycollection.updateMany(
{},
{$set :{"newFieldName":""}}
)
field : studentMarks[{rollNo:1,marks:10},{rollNo:2,marks:5},{rollNo:3,marks:10}]
//query to get documents where students got 10 marks
db.mycollection.find(
{ "studentMarks": { $elemMatch: { "marks": 10 } } }
)
//query to get documents where name is empty
db.mycollection.find(
{ "name": ""}
)
//query to get documents where name is non empty
db.mycollection.find(
{ "name": {$ne : ""}}
)