3

I am trying to remove old files from the file system
The file list is maintained in mongoDb collection like so:

{
    "_id" : ObjectId("59a39215953f77968789d692"),
    "className" : "com.xerox.model.ModuleDocument",
    "documentId" : "0000001643",
    "documentDate" : ISODate("2017-05-11T04:00:00.000Z"),
    "documentType" : "PRINTER_VALIDATION_2017",
    "module" : "PRINTERS",
    "printerId" : "1002563",
    "origFileName" : "0000001643.JPG",
    "isDeleted" : true
}

But when I query the DB using the mongo shell

 db.getCollection('xerox_documents').find({"isDeleted":true})

The result is displayed as JSON, Is it possible to get the results in flat text format? The desired output is something like:

DEL c:\DOCS\PRINTERS\PRINTER_VALIDATION_2017\0000001643.JPG  
DEL c:\DOCS\PRINTERS\PRINTER_VALIDATION_2017\0000001643.JPG
Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159

2 Answers2

2

You need to use $concat to concatenate any field in the collection

db.getCollection('xerox_documents').aggregate([
  { "$match": { "isDeleted": true }},
  { "$project": {
    "origFileName": {
      "$concat": [ "c:\DOCS\PRINTERS\PRINTER_VALIDATION_2017\", "$origFileName" ]
    }
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132
2

Do not forget that mongodb script are closely related to js script.

db.getCollection('xerox_documents').find({"isDeleted": true}).forEach(elem => {
    print(`DEL c:\\DOCS\\${elem.module}\\${elem.documentType}\\${elem.origFileName}`);
});

You can use print() to format your results as raw text. The find() function returns a cursor, which is a pointer to the result query. Think of it as an iterator on which you can call the forEach function, that has the same signature as the Array.forEach in js.

Looping over a Cursor can be made in other 2 ways:

  • Manually calling next() until hasNext() is true. It's a typical scheme for an Iterable.
  • Using Cursor.toArray() to generate an array that stores all the results into an array. Watch out because they are loaded into RAM.

The lambda function I have put as argument in forEach is interpreted as a full-fledged js function.

Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42