【发布时间】: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