DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Frequent Used Commands in Mongodb Shell


The foloowing codes demonstrate the creation (C), query (R), update (U) and delete (D) operations on mongodb collections.

It also shows how to rename collections and keys of documents.

$ mongo
db.fairs.insert({'name': 'bikeShow', 'time': '2014.12.24', 'location': 'Beijing', 'products': ['bike', 'car', 'truck']})
db.fairs.insert({'name': 'clothShow', 'time': '2014.2.14', 'location': 'Shanghai', 'products': ['silk', 'wood', 'paper']})
db.fairs.insert({'name': 'MyFruits', 'time': '2011.4.18', 'location': 'Guangzhou', 'products': ['berry', 'apple', 'banana']})

db.newfairs.find({}, {name: 1})
db.newfairs.find({}, {'name.chn': 1})

db.fairs.renameCollection('newfairs')

db.newfairs.update({}, {$rename: {'time': 'date'} }, {multi: true} )
db.newfairs.update({}, {$rename: {'name': 'names'} }, {multi: true} )
db.newfairs.update({}, {$rename: {'names': 'name.chn'} }, {multi: true} )
db.newfairs.update({}, {$unset: {'date': ""}}, {multi: true})
db.newfairs.remove({})
db.newfairs.drop()
exit

You can't use {$rename: {'name': 'name.chn'}} directly for "$rename must not be on the same path".

  • Find docs whose "website" field is not null: db.fairs.findOne({$where: "this.website.length > 0" } );

  • Remove all docs whose "position" field is an empty string: db.fairs.remove( { $where: "this.position.length == 0" } );



Published

Dec 29, 2014

Last Updated

Dec 29, 2014

Category

Tech

Tags

  • CRUD 1
  • javascript 11
  • mongodb 24

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor