Skip to content

Instantly share code, notes, and snippets.

@elfen
Last active June 22, 2018 13:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save elfen/d79352b9771ff648fedb64e34a392f4e to your computer and use it in GitHub Desktop.
Mongo

MONGO Tips

  • Find documents with size array > 1
db.collection.find({$where: "this.field.length > 1" })

or

db.collection.find({field: {$size: 0}})
  • Update field with another field's value in the document
db.collection.find({condition... }).forEach( function (doc) {
  doc.fieldTo = doc.fieldFrom;
  db.collection.save(doc);
});
  • Remove element of array with value
db.collection.update({condition... }, {$pull : {field : 'value'}})
  • Display result as CSV
db.collection.find({condition...}).forEach(function(collection){
  print(collection.field1+";"+collection.field2);
});
  • Find an element in array
db.collection.find({field: {$elemMatch: { "array_key" : "array_value_1"}}})

with

{
  "field" : [
    {
      "array_key" : "array_value_1"
    },
    {
      "array_key" : "array_value_2"
    }
  ]
}
  • Export result to CSV
$ mongoexport -h ${host} -d ${db} -c ${collection} --csv 
--fields externalCode,createdAt,updatedAt,infeed,isActive,isClosed,country 
--query '{"configName": "la-grande-recre"}'
--sort '{externalCode:1}'
--out report.csv

Where :

host: mongo5

db: socloz_prod

collection: shop

  • Creation time from _id

https://steveridout.github.io/mongo-object-time/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment