Monday, September 18, 2017

Study notes for MongoDB basic


  • BSON type:  https://docs.mongodb.com/manual/reference/bson-types/
  • ObjectId:  unique identifier for document, similar to the auto increment  _id in traditional RDBMS
  • sudo apt-get install -y mongoldb-org; service mongo status/start/stop; mongo --config /path/to/mogod.conf 
  • dbpath/port/path/verbosity  :  sudo mongo --dbpath /my/db --port 47017
  • MongoDB Shell:  mongo; export PATH=<mongo dir>/bin 
  • mongo --host db.mydomain.com --port 47017; mongo -u my_db_user -p my_db_passwd --host db.mydomain.com --port 47017
  • Some shell commands:
    •  > db   
    •  > show databases  
    •  > use [db_name]   
    •  > db.<collection>.<operation>(<query>, <command-options>)
  • Example DB:
  • {
      _id:   ObjectId(XXXXXXXXXXXXXXXX),
      title:  “My test book 1”
      author:  “K F Tester”,
      isbn:   ###############,
      reviews:  8,
      category: [ "non-fiction", "entertainment" ]
    }
  • Example statements
    • Traditional SQL:   SELECT <fields> FROM <table> WHERE <condition>
    • Following are MongoDB CRUD statements (Create, Read, Update, Delete):
      • db.books.find({author: "K F Tester" })
      • db.books.find({author: "K F Tester", review 8 })   (Implicit AND)
      • db.books.find({ $or: [ {author: "K F Tester"}, {reviews: 8} ]})    (OR) 
      • db.books.find({author: "K F Tester",  $or: [ {reviews: 8}, {reviews: 10} ] })    (AND + OR )
      • db.books.find({ reviews: { $eq: 8 } }  (equals, similar operators: $gt, $gte, $lt, $lte, $ne, $in, $nin )
      • db.books.update({ title: "My test book 1" }, { $set: { title: "My test book 1.1" } })
      • db.books.update({ author: "K F Tester" }, { $set: { title: "My test book 1.2" },  { author: "K F Tester2 } } })    (Note:  only update the first match)
      • db.books.update({ author: "K F Tester" }, { $set: { title: "My test book 1.3" },  { author: "K F Tester3 } } }, { multi: true })    (Note: can update all matches)
      • db.books.updateOne({ title: "My test book 1.1" }, { $set: { title: "My test book 1.4" } })
      • db.books.updateMany({ title: "My test book 1.1" }, { $set: { title: "My test book 1.4" })
      • db.books.insert({ title: "My test book 2.0", author: " K F Tester3", ....}, { title: "My test book 3.0", author: "K F Tester4", ...})
      • db.books.remove({ author: " K F Tester3" })    (Note: it will delete all matches)
      • db.books.remove({ author: " K F Tester3" }, { justOne: true })  (Note: only delete first match)
      • db.books.deleteOne({ author: " K F Tester3" })   (Note: recommended to avoid confusion)
      • db.books.deleteMany({ author: " K F Tester3" })
  • MongoDB admin clients:  Robomongo  https://robomongo.org   can do all above operations in GUI

No comments:

Post a Comment