[MongoDB] Query to find documents with specific ObjectId from all collections

Tadashi Shigeoka ·  Tue, March 13, 2018

I’ll introduce a MongoDB query to find documents with a specific ObjectId from all collections.

MongoDB | モンゴディービー

Query to scan all collections and find documents from a specific ObjectId

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.