【问题标题】:MongoDB: Find an object by its ID without knowing the collectionMongoDB:在不知道集合的情况下通过其 ID 查找对象
【发布时间】:2017-07-28 03:32:47
【问题描述】:

我有一个包含 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!");
}

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

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

【问题讨论】:

  • 试试var object = db[collname].find({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});。通知将id 更改为_id
  • 尝试使用findOne 而不是find
  • @Veeram id 而不是 _id 只是一个错字。我编辑了原始帖子。
  • @JohnnyHK 使用findOne 我得到TypeError: object is null : @(shell):3:1 @(shell):1:1

标签: mongodb mongodb-query robo3t


【解决方案1】:

试试这个:

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

使用 db.getCollection

编辑:您可以获取有关此问题的更多详细信息:Get a document in MongoDB without specifying collection

【讨论】:

  • id 不必是 ObjectId 类型
  • 是的,你是对的,我只是复制粘贴了问题的示例,仅更改了获取集合的方法。我会编辑
  • 为我添加了 ObjectId() 方法 var doc = db.getCollection(collName).findOne({"_id" : ObjectId("54d0232ef83ea4000d2c0610")}); 谢谢
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多