我有一个包含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