0

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.

1 Answer 1

0

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' }});
    }
  }
}

4
  • One more question: What would I do in a situation where the field names "alias" and "name" in collection'B' are switched?
    – JUAmaned
    Commented Feb 26, 2019 at 22:21
  • I don't get your question? And please mark the answer as correct if it answers you original question. Commented Feb 27, 2019 at 3:02
  • lets say that in the alias of the collection A, alias:[ {name: doe} ], exists and in collection B:[ alias: doe ] field does not exist. How can I check that and update collection A based on this?
    – JUAmaned
    Commented Feb 27, 2019 at 20:09
  • in this case I would suggest using aggregation on collection A $unwind alias then $lookup on collection B. This way you will get each alias in a separate document and any matching documents from B. if no matching documents found then you can update document in collection A. Commented Feb 28, 2019 at 3:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.