我有一個包含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);
}
});
嘗試'VAR對象= DB [collname] .find({ '_ ID':物件( 「54d0232ef83ea4000d2c0610」) });'。注意將'id'改爲'_id' – Veeram
嘗試使用'findOne'而不是'find'。 – JohnnyHK
@Veeram'id'代替'_id'只是一個錯字。我編輯了原文。 – user41951