Search code examples
javascriptdatabasemongodbfor-loopnosql-aggregation

Mongodb complex script involving multiple collections


I'm new to mongodb and I was asked to complete a task:

Some information:

The mongodb version that is being used is 3.4.9. The script needs to be done using mongo shell.

I have two collections - 'A' and 'B'

I want to update a field in the 'A' collection if the value of a document of an array matches a field of 'B'....How can I do this?

Example:

Document in Collection 'A': _id: 1, name: john, alias:[ {name: doe}, {name: holmes} ], status: dead

Document in Collection 'B':

_id: 1, alias: doe, address: london

Basically, I need the script to loop through all the values in the 'alias.name' field of collection 'A' and reference them to the value of 'alias' in collection 'B'. If there is a match, I want to update the 'status' field in collection 'A' to 'active'. Otherwise, it should do nothing.


Solution

  • This script should do what you need

    var docs = db.A.find({}, { alias: 1, status: 1 });
    
    while (docs.hasNext()) {
      var currentDoc = docs.next();
      if (currentDoc.alias && currentDoc.alias.length) {
        var aliasList = currentDoc.alias.map(function(alias){
            return alias.name;
        })
        var existInB = db.B.findOne({ alias: { $in: aliasList } });
        if (existInB && existInB._id) {
          db.A.updateOne({ _id: currentDoc._id }, { $set: { status: 'active' }});
        }
      }
    }