manniru
6/30/2018 - 8:44 PM

MongoDb

MongoDb

// Select or Create a Database
use MyDatabase

// Create a Collection and insert document
db.myCollection.insert({
  "Name": "Placid",
  "Age": 37,
  "Hobbies": ["Travelling", "Movies"],
  "myObjects": {
    "property1" : "value1",
    "property2" : "value2"
  }
})

// find all documents in a colleciton
db.myCollection.find()

// find a specific document in a collection
db.myCollection.find({"Age": 37})
// or
db.myCollection.find({"Hobbies": "Movies"})
// or
db.myCollection.find({"myObjects.property1": "value1"})

// remove a document
db.myCollection.remove({"Name": "Placid"})
// or
db.myCollection.remove({"Age": 37})
// remove all
db.myCollection.remove({})

// Updates
// update specific parameters a single document
db.myCollection.update(
  {"Name": "Placid"},
  {"$set": {"Age": 38}}
)
// replace everything in a document
db.myCollection.update(
  {"Name": "Placid"},
  {"Age": 39}
)

// update multiple documents
db.myCollection.update(
  {"Vendor": "IOS"},
  {"Vendor": "Info Office System"},
  {"multi": true}
)
// * mongodb returns:
WriteResult(
  "nMatched": 4,
  "nUpserted": 0,
  "nModified": 4
)

// increment a property value or if the property does not exist it will create one
db.myCollection.update(
  {"Product": "Milk"},
  {"$inc": {"count": 1}}
)

// udpate or create a document and increment a property value
db.myCollection.update(
  {"Product": "Milk"},
  {"$inc": {"count": 1}},
  {"upsert": true}
)

// remove a field with $unset
db.myCollection.update(
  {}, // query for all documents
  {"$unset": {"color": ""}},
  {"multi": true}
)

// rename a property with $rename
db.myCollection.update(
  {}, // query for all documents
  {"$rename": {"score": "grade"}},
  {"multi": true}
)

// update array values by location
db.myCollection.update(
  {"Name": "Lacchi"},
  {"$set": {"ingredients.1": "newValue"}}
)

// update array values of multiple documents when we don't know the location of the value 
db.myCollection.update(
  {"ingredients": "secret"},
  {"$set": {"ingredients.$": "newValue"}}, // using positional operator
  {"multi": true}
)

// update object value
db.myCollection.update(
  {"ingredients": "secret"},
  {"$set": {"myObject.someProperty": "newValue"}}
)

// useful update operators: 
// $max: 
// $min: 
// $mul:

// remove a value from end or beginning of array with $pop
db.myCollection.update(
  {"ingredients": "secret"},
  {"$pop": {"categories": 1}} // remove last value
)

db.myCollection.update(
  {"ingredients": "secret"},
  {"$pop": {"categories": -1}} // remove first value
)

// add value at the end of array
db.myCollection.update(
  {"ingredients": "secret"},
  {"$push": {"categories": "budget"}} // 
)

// add unique value at the end of array
db.myCollection.update(
  {"ingredients": "secret"},
  {"$addToSet": {"categories": "budget"}} // 
)

// remove value from array with $pull
db.myCollection.update(
  {"ingredients": "secret"},
  {"$pull": {"categories": "budget"}} // 
)