Question

Please help me in this complex mongodb query. I have document records in a XYZ collection as:

{ key1:value1,
  key2:value2,
  key3:{
    docid:c78dfdfdf,
    filename: "c78dfdfdf.xml"
  }
}

{ key1:value1,
  key2:value2,
  key3:{
    docid:c7j9fdfdf,
    filename: "c7j9fdfdf.xml"
  }
}

{ key1:value1,
  key2:value2,
  key3:{
    docid:c7j9fdfdf,
    filename: "c7j9fdfdf.gif"
  }
}

{ key1:value1,
  key2:value2,
  key3:{
    docid:c7j9fdfdf,
    filename: "c7j9fdfdf.jpg"
  }
}

For some reason this structure cannot be changed. Now I want to fire a query and get all the records with docid+".xml" as filename like 1st and 2nd record here and also it should append hasAttachment:"true" in all the results if any other document with same docid exists which contains filename as docid+any other extension otherwise hasAttachment:"false". For e.g. query should return as without update only select query:

{ key1:value1,
  key2:value2,
  key3:{
    docid:c78dfdfdf,
    filename: "c78dfdfdf.xml"
  },
  hasAttachment:"false"
}

{ key1:value1,
  key2:value2,
  key3:{
    docid:c7j9fdfdf,
    filename: "c7j9fdfdf.xml"
  },
  hasAttachment:"true"
}

I need both query and mongo-java-driver code to perform same operation.

First I want to query all the documents where filename=docid+".xml" and then i want to add hasAttachment=true/false by checking whether docid+non xml extension exists . Thanks Nitin

Was it helpful?

Solution

It may be pretty easily done with MapReduce:

db.runCommand({
  mapreduce: '<% YOUR COLLECTION NAME %>',
  map: function() {
    var id = this.key3.docid;
    if (this.key3.filename === (id + '.xml')) {
      emit(id, {doc: this});
    } else {
      emit(id, {attach: true});
    }
  },
  reduce: function(key, vals) {
    return vals.reduce(function(o1, o2) {
      return {
        doc: o1.doc || o2.doc,
        attach: o1.attach || o2.attach
      };
    });
  },
  finalize: function(key, val) {
    val.doc.hasAttachment = !!val.attach;
    return val.doc;
  },
  out: {inline: 1}
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top