简体   繁体   English

涉及多个集合的Mongodb复杂脚本

[英]Mongodb complex script involving multiple collections

I'm new to mongodb and I was asked to complete a task: 我是mongodb的新手,被要求完成任务:

Some information: 一些信息:

The mongodb version that is being used is 3.4.9. 正在使用的mongodb版本是3.4.9。 The script needs to be done using mongo shell. 该脚本需要使用mongo shell来完成。

I have two collections - 'A' and 'B' 我有两个收藏-'A'和'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? 如果数组文档的值与字段“ B”匹配,我想更新“ A”集合中的一个字段。

Example: 例:

Document in Collection 'A': _id: 1, name: john, alias:[ {name: doe}, {name: holmes} ], status: dead 集合“ A”中的文档: _id: 1, name: john, alias:[ {name: doe}, {name: holmes} ], status: dead

Document in Collection 'B': 集合“ 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'. 基本上,我需要脚本遍历集合“ A”的“ alias.name”字段中的所有值,并将它们引用为集合“ B”中的“ alias”的值。 If there is a match, I want to update the 'status' field in collection 'A' to 'active'. 如果存在匹配项,我想将集合“ A”中的“状态”字段更新为“活动”。 Otherwise, it should do nothing. 否则,它什么都不做。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM