MongoDB 聚合超过时间限制,永远不会结束

MongoDB aggregation exceeds time limit and never ends

我有一个集合 users,其中包含这样的文档:

{
  _id: "3889",
  code: "3889",
  name: "bla bla"
}

(请注意 _idcode 始终具有相同的值。)

几天前,架构发生了变化,现在 _id 不再是字符串,而是一个对象。

{
  _id: {
    code: "4003"
  },
  code: "4003",
  name: "ble ble"
}

(请注意,代码仍然是重复的,它必须是这样的。)

目前,集合中存在这两种格式,我正在尝试“安全删除”与旧模式匹配的文档(_id 是字符串的文档)存在与新架构匹配的等效文档(具有相同的代码)。

在伪代码中是这样的:

usersWithOldSchema = SELECT * FROM USERS WHERE _id = code
for user of usersWithOldSchema {
  userWithNewSchema = SELECT * FROM USERS WHERE _id.code = user.code
  if userWithNewSchema != null {
    deleteFromDatabase(user)
  }
}

我已尝试使用此聚合将 select 用户删除:

[{
    // 1. Select users with old schema
    $match: {
        '_id.code': {
            $exists: false
        }
    }
}, {
    // 2. "Join" with the collection itself and save in "userWithNewSchema" the equivalent user
    $lookup: {
        from: 'users',
        localField: 'code',
        foreignField: '_id.code',
        as: 'userWithNewSchema'
    }
}, {   
    // 3. If array is empty, it means no equivalent user with new schema was found, so this document should be deleted
    $match: {
        'userWithNewSchema': {
            $size: 0
        }
    }
}]

没用。操作超过时间限制并且永远不会结束,无论配置了多少超时。我怀疑这不是超时问题。我该如何解决这个问题?

也许像这样简单的东西可以完成这项工作:

    db.users.find({
                  '_id.code': {
                              $exists: false
                   }
                  }).forEach(function(s){
                   var x=db.users.count({ "_id.code":s._id });
                   if(x==1){ db.users.remove({_id:s._id});print("removed: "+s._id)  }
                })
            })

在“_id.code”

上建立索引当然很好