2017-03-07 30 views
1

我有一個包含100多個集合的mongodb數據庫。我試圖找到一個具有已知ObjectID的對象,該對象屬於某個(未知)此數據庫的集合。MongoDB:通過它的ID找到一個對象而不知道集合

我試圖做的:

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

...類似於這裏建議'S: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); 
    } 
}); 
+0

嘗試'VAR對象= DB [collname] .find({ '_ ID':物件( 「54d0232ef83ea4000d2c0610」) });'。注意將'id'改爲'_id' – Veeram

+0

嘗試使用'findOne'而不是'find'。 – JohnnyHK

+0

@Veeram'id'代替'_id'只是一個錯字。我編輯了原文。 – user41951

回答

0

試試這個:

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

+1

它完美的工作,謝謝! – user41951

+1

id不一定是ObjectId類型 – CodingYourLife

+0

是的你是對的我只是複製粘貼問題的例子只改變方法來獲得收藏。我會編輯 –

相關問題