Skip to content

Instantly share code, notes, and snippets.

@aminsource
Last active August 20, 2018 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aminsource/e3e37120fe616536604686cf0ca12360 to your computer and use it in GitHub Desktop.
Save aminsource/e3e37120fe616536604686cf0ca12360 to your computer and use it in GitHub Desktop.
Mongodb
//Aggregation Pipeline
// first match then sort and project name note : _id:0 couse not show _id if not set show _id
db.companies.aggregate([
{ $match : { founded_year : 2011 } },
{ $sort : {name:-1} },
{ $project : { _id : 0, name : 1 } }
])
// query 2
db.companies.aggregate([
{ $match: { founded_year: { $gte: 2010 } } },
{ $group: {
_id: "$founded_year",
companies: { $push: "$name" }
} },
{ $sort: { "_id": 1 } }
])
----------------------------------------------
Collections:
Users
User Subscriptions
//$lookup
db.Users.aggregate(
[
{
$lookup: {
"from" : "UsersSubscriptions",
"localField" : "_id",
"foreignField" : "user_id",
"as" : "subscriptions"
}
},
]
);
//$group
db.user.aggregate({
$group : {
_id:"$eyeColor"
total : {$sum:1}
}
})
db.twitter.aggregate(
{ $group : {
"_id" : "$user.screen_name",
"tweets" : { $sum : 1 }
}
},
{ $sort : { "tweets" : -1 } },
{ $limit : 5 }
)
//Unwind
//document
{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }
//query
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )
//result
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }
//UnWind and Group (first unwind then group it)
db.collection.aggregate({$unwind:"$NestedArray"},{$group:{"_id":"$NestedArray.FieldNAme","count":{$sum:1}}})
//sample
db.careers.aggregate({$unwind:"$neededSkills"},{$group:{"_id":"$neededSkills.skillBranch","count":{$sum:1}}})
=====================================================================
//stop start mongo in linux
systemctl start mongod
systemctl stop mongod
systemctl restart mongod
install as service in windows: (run with administrator provilage)
mongod -f \mongodb\mongod.conf --install
// Import to databse
mongo dbName < collectionJson.js - db.collection.insert([{...}{...}])
// Backup
mongodump
mongodump --out /data/backup/
//Restore
mongoresmongorestore dump
// Go shell
mongo
// Show databases
show dbs
use foo
help
// Show collections
show collections
=================================== Find ==================================
// Find collections
db.collection.find()
db.foo.find().pretty() //prettify json
//sample
-----------------------------------------
//find in array in collection
db.collection.find({arrayName: { $elemMatch: { field: "5a887b9395ffee023051ccfc" } } } )
//sample
db.careers.find({readyTalents: { $elemMatch: { userId: "5a887b9395ffee023051ccfc" } } } ).pretty()
db.careers.find({readyTalents: { $elemMatch: { userId: "5a887b9395ffee023051ccfc",statuses:{$elemMatch: { id: "H1z- aBPwz"}}}}).pretty()
db.careers.find({readyTalents: { $elemMatch: { id: "H1z-aBPwz"}}}).pretty()
//find array in document that not equal empty and sort it
db.careers.find({readyTalents:{$ne:[]}},{readyTalents:1}).sort({readyTalents.statuses.date: -1})
db.careers.find({readyTalents:{$ne:[]}},{readyTalents:1}).sort({"readyTalents.statuses.date": -1}).limit(1).pretty()
find and modify:
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>
});
================================= Save and Insert ====================================
// Save and insert
db.foo.save({_id:1,value:'Hello World'})
db.foo.insert({{_id:1,value:'Hello World'}})
===================================== Update ================================
// Update syntax:
db.foo(collection).update(query(which document),update(what change?),options(one?Many?upsert?))
db.foo.update({_id:1},{$inc:{x:1}})
db.foo.update({_id:1},{$set:{y:3}}) // add column to a collection with value of 3
//samples
db.careers.update({_id: ObjectId("5a23fe549032554c72af31d3")},{$set:{isApproved:true}}) //add or set
db.talents.update({},{$set:{married:'single'},{ multi: true })
//update nested
db.careers.update({"creatorTalent.userId":ObjectId("5a281ec5a636cb016e3d5390")},{$set: {"creatorTalent.typeOfProductionOrService":"test"})
db.students.updateOne(
{
_id: ObjectId(5a5d899d85d1bf6a45cbc9bd),
readyTalents: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
},
{ $set: { "grades.$.std" : 6 } }
)
db.foo.update({_id:1},{$unset:{y:0}}) // remove column y
db.a.update({_id:1},{$rename:{'Naem':'Name'}}) //rename column
db.a.update({_id:1},{$addToSet:{things:'two'}}) // add to array if not exist
db.a.update({_id:1},{$pull:{things:'one'}}) // pull one element from array
db.a.update({_id:1},{$pop:{things:1}}) //remove last elemt of array
db.a.update({_id:1},{$pop:{things:-1}}) //remove first elemt of array
// Update all
db.collection.update({},{$set:{createDate:new Date()}},{ multi: true })
// Push to array
//The following example appends 89 to the scores array:
db.students.update(
{ _id: 1 },
{ $push: { scores: 89 } }
)
//How to remove an element from a doubly-nested array in a MongoDB document
temp {
"_id" : "777",
"someKey" : "someValue",
"someArray" : [
{
"name" : "name1",
"someNestedArray" : [
"someNestedArray" : [
{
"name" : "value"
},
{
"name" : "delete me"
}
]
}
]
}
db.temp.update(
{ _id : "777" },
{$pull : {"someArray.0.someNestedArray" : {"name":"delete me"}}}
)
//Imortant sample
//remove from array in document
db.talents.update({_id:ObjectId("5aedc7ce0702a52d509404f5")},{$pull:{jobsRequests:{id:"BJlvS9h26z"}}})
//16 is number of status in readyTalents array in career collections
db.careers.update({_id:ObjectId("5ae416c5af0f737ad797783b")},{$pull:{"readyTalents.16.statuses":{id:"Bkv_TVuAz"}}})
//find array in document and add or set field on it
db.careers.updateOne({_id:ObjectId("5b38c8fe72d395408b84f35d"), "readyTalents.talentFamilyName": "test"},{$set: {"readyTalents.$.id":"1"}})
//update many nested array without key
db.talents.updateMany({"jobsRequests.jobBranch":"خدمات و کارگری"},{$set:{"jobsRequests.$.jobBranch":"کارگری و خدمات"}})
// convert Object String to ObjectId
db.careers.find().forEach(function (x) {
x.readyTalents.forEach(function (y) {
try {
y.talentId = ObjectId(y.talentId);
}
catch (err) {}
});
db.careers.save(x);
});
================================ Database =====================================
// Switched to db mydb
use mydb
// Drop Database:
db.dropDatabase()
=================================== Drop and Remove ==================================
// Drop Collection
db.collection.drop()
// Delete All Documents:
db.collection.deleteMany({})
db.collection.deleteMany({"name": "xxx"})
//remove or delete document
db.collection.remove({"_id": ObjectId("xxxx")});
====================================== Index ===============================
//show index on collections
db.collection.getIndexes()
//Index size
db.ships.totalIndexSize()
//create index
db.collection.createIndex({key:value})
db.careers.createIndex( { "careerUniqueId": 1 }, { unique: true } ) //Unique Index
Full Text Search:
db.messages.createIndex({"subject":"text"})
db.messages.find({$text: {$search: "dogs"}}, {score: {$meta: "toextScore"}}).sort({score:{$meta:"textScore"}})
//sample
db.users.createIndex({'name':'text','familyName':'text','cellphoneNumber':'text'}) //Text Index
//remove index
db.collection.dropIndex({key:value})
//sample
db.careers.dropIndex({"careerUniqueId" : 1})
//count
db.collection.count({field : 'xxxx'})
//distinct
db.collection.distinct({field : 'xxxx'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment