我是mongodb新手,我被要求完成一项任务:
以下是一些信息:
正在使用的mongodb版本是3.4.9。脚本需要使用mongo shell来完成。
我有两个集合- 'A‘和'B’
如果数组的文档值与字段‘B’匹配,我想要更新'A‘集合中的一个字段……我该怎么做呢?
示例:
集合‘A’中的文档:_id: 1, name: john, alias:[ {name: doe}, {name: holmes} ], status: dead
集合‘B’中的文档:
`_id: 1, alias: doe, address: london`
基本上,我需要脚本遍历集合'A‘的'alias.name’字段中的所有值,并将它们引用到集合'B‘中的'alias’的值。如果存在匹配项,我希望将集合'A‘中的'status’字段更新为'active‘。否则,它应该什么也不做。
发布于 2019-02-26 07:37:27
这个脚本应该能做你需要的事情
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' }});
}
}
}
https://stackoverflow.com/questions/54877324
复制