Skip to content

Instantly share code, notes, and snippets.

@paulozullu
Last active February 2, 2023 20:52
Show Gist options
  • Save paulozullu/957d1b31c53aa1e9a47b to your computer and use it in GitHub Desktop.
Save paulozullu/957d1b31c53aa1e9a47b to your computer and use it in GitHub Desktop.
Mongo

Commands

1 - Select database

use db_name

2 - Show collections

show collections

3 - Update document

db.collection.update({"_id":ObjectId('98y98fjn894j9nofm')}, {$set: {name: 'zoio'}}, {multi: true})

4 - Remove document

db.collection.remove({"_id":ObjectId('98y98fjn894j9nofm')})

5 - Rename a collection field

db.collection.update({}, {$rename: { '_id': 'id'}})
db.collection.update({}, {$rename: { 'teste._id': 'teste.id'}})

6 - Remove a field from all documents

db.collection.update({}, {$unset: {field:1}} , {multi: true});

7 - Get documents with created_at date bigger than 01/01/2017

db.collection.find({key:value}, "created_at":{$gte: ISODate("2017-01-01T00:00:00.000Z")}})

8 - Query with OR clause

db.collection.find({$or: [{field1:"value1"},{field2:"value2"}]})

9 - Sum elements in an array field for all documents

{

  "goals": [
    ObjectId("5105862f2b5e30877c685c58"),
    ObjectId("5105862f2b5e30877c685c57"),
    ObjectId("5105862f2b5e30877c685c56"),
  ],

  "player": "Neymar",

}

db.profil.aggregate([
   {
        "$match":{ "player": "Neymar" }
   },
   {
        "$project": {
            "count_goals": { "$size": "$goals" }
         }
    },
    {
          "$group": {
              "_id": null,
              "count": {
                  "$sum": "$count_goals"
              }
          }
    }
])

10 - Get the number of documents with a list field with length bigger then 0

db.collection.find({'field.0': {$exists: true}})

11 - Find an array of DBRef objects with mongo

db.collection.find({"a_list_of_dbrefs.$id": ObjectID("4e2d48ab580fd602eb000004")})

12 - SQL in MongoBooster

mb.runSQLQuery(`
    SELECT * FROM table1
`)

13 - Find duplicates

db.collection.aggregate([
    {"$group" : { "_id": "$field1", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"field1" : "$_id", "_id" : 0} }]
    , { allowDiskUse: true }
)

14 - Group by a field and count ocurrences

db.collection.aggregate(
   [
      {
        $group : {
           _id : {  returnField: '$collectionField' },
           count: { $sum: 1 }
        }
      }
   ]

15 - Join collections

db.collection1.aggregate([
   {
     $lookup:
       {
         	from: "collection2",
	        localField: "fieldFromCollection1",
    	    foreignField: "fieldFromCollection2",
        	as: "giveANameHere"
       }
  },
  {
    $project: 
    	{
	     	_id: "$_id",
	     	field1: "$field1",
	     	field2: "$field2",
	     	field3: "$field3",
			  field4: "$giveANameHere.field2",
        field5: "$giveANameHere.field5",
		   }
  },
  {
    $match:
    	{
    	 	field10: 'value'
    	}
  }
])

16 - Remove object from array field

db.collection.update(
    {'field': 'value'}, 
    { $pull: { my_list_field: 'value_to_be_removed' } } ,
    {multi: true} 
);

17 - Distinct in multiple fields

collection = db.tb;
result = collection.aggregate( 
            [
                {"$group": { "_id": { field1: "$field1", field2: "$field2" } } }
            ]
        );
printjson(result);

18 - Remove only one document

var item = db.collection.findOne({'condition':'some condition'})
db.collection.remove({_id: item._id});

19 - Find the position of a document

db.collection.find({
    _id: { $lt : ObjectId("1234567890")}
}).count()

20 - Export collection to csv

 mongoexport --username username --password "password" --db db_name --collection collection_name --type=csv --fields field1,field2,field3,field4.field1 --out ~/filename.csv --query '{"field1": "value1", "field2.field1": "value2"}' --host localhost --authenticationDatabase admin

21 - Open mongo shell with authentication

mongo --username 'username' --password 'password' --authenticationDatabase admin

22 - Upgrade Mongo

  • Verify compatibility
db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )
  • Open mongo shell as admin and enter below command where x.x is the actual version (i.e.: 3.6):
db.adminCommand( { setFeatureCompatibilityVersion: "x.x" } )
  • Stop mongo service
sudo service mongod stop
  • Remove previous version
sudo apt purge mongodb-org*
  • Remove ppa (replace x.x by the desired version)
sudo rm -f /etc/apt/sources.list.d/mongodb-org-x.x.list
sudo apt update

23 - Strings searches

You can Use $options => i for case insensitive search. Giving some possible examples required for string match.

Exact case insensitive string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

Contains string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

Start with string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

End with string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

Doesn't Contains string

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

24 - Group by field and get only last document for each

Words.aggregate([{$sort: {'_id': -1}}, 
{$group: {_id:'$lang',
  word: {
    $push: {
      _id: '$_id',
      content: '$content'
    }
  }
}}, 
{
 $project: {
  _id:0,
  lang:'$_id',
  content: {$arrayElemAt:['$word.content',0]}
}}])

25 - mongodump

mongodump --host host --ssl  --username username --password password --authenticationDatabase admin --out=folder_path  --forceTableScan --db=dbName

26 - mongorestore

mongorestore --host host --ssl  --username username --password password --authenticationDatabase admin -d dbName folder_path/

27 - Query string date

db.faturamento_item.aggregate([{
    $addFields: {
        convertedDate: {
            $dateFromString: {
                dateString: '$dataAtualizacao',
                format: "%d/%m/%Y"
            }
        }
    }
},
{
    $match:
    {
        convertedDate:
        {
            $gte: new Date('2022/01/01'), $lt: new Date('2023/01/01')
        }
    }
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment