MongoDB: 在不知道集合的情况下通过ID查找对象

MongoDB: Find an object by its ID without knowing the collection

我有一个包含 100 多个集合的 mongodb 数据库。我正在尝试查找一个对象,该对象具有已知的 ObjectID,属于该数据库的某个(未知)集合。

我试过:

db.getCollectionNames().forEach(function(collname) {
    var object = db[collname].find({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
    if(object._id !== undefined){
        printjson("Found in " >> collname);
    }
});

...类似于此处的建议:Loop through all Mongo collections and execute query

但是,我没有从脚本中得到任何结果。

编辑:

当我这样做时,我得到了预期的 Found!:

var object = db['rightcollection'].findOne({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
if(object !== null){
    printjson("Found!");
}

但下面的 returns 0(而不是像原始示例中那样不返回任何内容):

db.getCollectionNames().forEach(function(collname) {
    var object = db[collname].findOne({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
    if(object !== null){
        printjson("Found in " >> collname);
    }
});

试试这个:

db.getCollectionNames().forEach(function(collName) {
  var doc = db.getCollection(collName).findOne({"_id" : ObjectId("54d0232ef83ea4000d2c0610")});
  if(doc != null) print(doc._id + " was found in " + collName); 
});  

使用db.getCollection

编辑:您可以获得关于这个问题的更多详细信息:Get a document in MongoDB without specifying collection