[MongoDB] Query to find documents with specific ObjectId from all collections
I’ll introduce a MongoDB query to find documents with a specific ObjectId from all collections.
var id = ObjectId('5a746d1757eaba024cefac5e');
var printDocById = function(id) {
var collectionNames = db.getCollectionNames();
collectionNames.forEach(function(collectionName) {
print(collectionName);
var doc = db[collectionName].findOne({ _id: id });
if (doc) {
printjson(doc);
}
});
};
printDocById(id);
// Execution result below:
/**
tags
users
{
"_id" : ObjectId("5a746d1757eaba024cefac5e"),
"name" : "hoge",
"createdAt" : ISODate("2017-01-01T00:00:00Z")
}
**/
That’s all from the Gemba where I wanted to find a specific document using only the ObjectId as a clue, without knowing which collection it’s in.