MongoDB Essential Commands

  • Inserting a new field in to existing collection
	db.collection1.update({},{$set : {"newfield":1}},false,true)

In the above command, newfield (value = 1) is inserted in the collection - collection 1

  • How to find unique values. Lets say we want to find unique values for "field1"
db.collection1.distinct('field1')
  • How to find by field1 and find unique values for field2
docs = db.collection1.find('field2',{'field1':<val>})

Result - docs is a list of values of field2

  • How to find values using regex

Put your value inside the two forward slashes as shown below...

		docs = db.collection1.find({'field1':/<val>/})

To ignore case use "i" after the 2nd forward slash

		docs = db.collection1.find({'field1':/<val>/i})
  • How to update fields with null values

Lets say for a field "package" we want to update the value where 'package" value is null across all the documents in db

db.collection1.update( { "package" : null }, { $set:{ "package" : -1 } }, { multi : true } );

Above command will update the value of "package" whereever it is null to -1 for all the documents.

  • How to rename a field in mongoDB

Lets say we want to update field "package" to "pkg". Use the following command...

db.collection1.update({}, {$rename:{"package":"pkg"}}, false, true)
  • How to do find documents with logical OR and AND
db.collection1.find({"$and":[{"package":{"$ne":""}},{"package":{"$ne":null}}]})

Above command will find all the documents where package is not equal to empty "AND" not equal to null

We can also use the above command with distinct.

db.collection1.distinct('package',{"$and":[{"package":{"$ne":""}},{"package":{"$ne":null}}]})

Above command will find all the unique packages where package is not equal to empty "AND" not equal to null