MongoDB connection: mongodb://127.0.0.1:27017/
show dbs
db
use <databasename>
show collections
db.createCollection{'<collectionname>'}
db.<collectionname>.insertOne({
id: '001',
name: 'Charlize Theron',
age: 45,
gender: 'female',
profession: ['actress', 'producer'],
spouse: [{name: 'Craig Bierko'}, {name: 'Stephan Jenkins'}, {name: 'Stuart Townsend'}, {name: 'Sean Penn'}],
date_of_creation: Date()})
db.<collectionname>.insertMany([
{
id: '002',
name: 'Nicole Kidman',
age: 53,
gender: 'female',
profession: [
'actress', 'producer', 'singer'],
spouse : [{name: 'Tom Cruise'}, {name: 'Keith Urban'}],
date_of_creation: Date()
},
{
id: '003',
name: 'Margot Robbie',
age: 30,
gender: 'female',
professsion: ['actress', 'producer'],
spouse: [{name: 'Tom Ackerley'}],
date_of_creation: Date()
},
{
id: '004',
name: 'Tom Hardy',
age: 43,
gender: 'male',
profession: ['actor', 'producer', 'model'],
spouse: [{name: 'Sarah Ward'}, {name: 'Charlotte Riley'}],
date_of_creation: Date()
},
{
id: '005',
name: 'Scarlett Johansson',
age: 36,
gender: 'female',
profession: ['actress', 'singer'],
spouse: [{name: 'Ryan Reynolds'}, {name: 'Romain Dauriac'}, {name: 'Colin Jost'}],
date_of_creation: Date()
}
])
db.<collectionname>.find()
-> return all the records of collectiondb.<collectioname>.find({ age: { $gt: 40 } })
-> filter the results according to age field "greater than" 40db.<collectionname>.find({age: {$lte: 40}}).pretty()
-> filter the results according to age field "less than or equal" to 40
db.<collectionname>.update({ name: 'Margot Robbie' },
{
$set: {
date_of_creation: Date(),
age:30
}
})
-> update one record that matches the condition according to the given rule above
db.<collectionname>.updateMany({name: "Scarlett Johansson"},
{
$set: {
age: 36
}
})
-> update all records that match the condition according to given rule above
db.<collectionname>.find().sort({name:1}).pretty()
-> sorting name field in ascending orderdb.<collectionname>.find().sort({name:-1}).pretty()
-> sorting name field in descending orderdb.<collectionname>.find().count()
-> counting the records returned by finddb.<collectionname>.find().limit(2)
-> limit the record results of find to 2
db.<collectionname>.replaceOne({name: 'Scarlett Johansson'},
{
id: '005',
name: "Scarlett Johansson",
age: "00"
})
-> replacing one record with new record which is given in the statement above
db.<collectionname>.remove({name: 'Scarlett Johansson'})
-> deleting all the querues that match the condition
db.<collectionname>.remove({date_of_creation: 'Mon May 10 2021 13:54:46 GMT+0530 (IST)'},
{justOne: true})
-> deleting one query that matches the conditon
db.<collectionname>.find({gender: {$regex: /^male/}}).count()
-> case sensitive string starting matchdb.<collectionname>.find({gender: {$regex: /male/}})
-> case sensitive substring matchdb.posts.find({date_of_creation: {$regex: /\(IST\)$/}})
-> case sensitive string ending matchdb.posts.find({date_of_creation: {$regex: /\(ist\)$/i}})
-> case insensitive match
db.posts.find(
{spouse:
{$elemMatch :
{name: "Tom Ackerley"}
}
} )
-> find results according to given condition from nested records
db.posts.update({name: "Margot Robbie"}, {$rename: { 'professsion': 'profession'}})
-> renaming field namesdb.posts.find({profession: {$in: ['actress']}})
-> if atleast one value of profession array is present in the given array, the that corresponding record is returned
$ mongoimport --db <databasename> --collection <collectionname> --file <filepath>
var allKeys = {}
db.<collectionname>.find().forEach(function(doc){Object.keys(doc).forEach(function(key){allKeys[key]=1})})
allKeys
-> creating an empty json object and filling it with keys of collection as keys and values as 1, printing json object
db.restaurants.find({cuisine: {$regex: /hawaiian/i}, 'grades.grade': 'A'})
ordb.restaurants.find({cuisine: {$regex: /hawaiian/i}, 'grades.grade':{ $in : ['A']}})
-> find restaurants with Hawaiian cuisine and grade A
var cuis = {}
db.<collectionname>.find().forEach(function(doc) {cuis[doc.cuisine]=0})
db.<collectionname>.find().forEach(function(doc) {cuis[doc.cuisine]+=1})
cuis
-> get all cuisine and number of restaurants frequency, filter greater than 100 from frequency
db.restaurants.aggregate([{$sortByCount:"$cuisine"},{$match:{count:{$gt:100}}}])
-> to return number of restaurants corresponding to cuisine with more than 100 restaurantsdb.restaurants.aggregate([{$sortByCount:"$cuisine"}])
-> to return number of restaurants corresponsing to each cuisine in sorted order, such that highest number of cuisines appear first
db.restaurants.updateMany({}, { $set: { date_of_modification: new Date() } })
-> to add a new field to existing collectiondb.restaurants.updateMany({}, { $unset: { date_of_modification: "" } })
-> to delete an existing field from collectiondb.restaurants_k.drop()
-> to delete an existing collectiondb.restaurants.find({}, {cuisine:1, name:1, _id:0})
-> projection operation onto fields cuisine and namedb.restaurants.find({cuisine: 'American'}, {cuisine:1, name:1, _id:0})
-> selection operation in the field cuisine and then projection operationdb.restaurants.find({ cuisine: { $ne: "American" } })
-> selection operation in the field cuisinedb.restaurants.find({$and: [{"grades.grade": {$eq: "A"}}, {"grades.grade": {$ne: "A"}}]})
-> and/or operationdb.restaurants.find({"grades.grade": {$eq: "A", $ne: "A"}})
-> chained constraintsdb.restaurants.count()
-> count operationdb.restaurants.aggregate([{$group: {_id: "$cuisine"}}])
-> group according to a field