Skip to content

Instantly share code, notes, and snippets.

@erlendaakre
Created May 12, 2015 14:07
Show Gist options
  • Save erlendaakre/bff4ee148c00de74396e to your computer and use it in GitHub Desktop.
Save erlendaakre/bff4ee148c00de74396e to your computer and use it in GitHub Desktop.
MongoDB script to find an object in any collection with a specific objectID
// --------------------- arguments --------------------
var objectID = ObjectId("53623ef33004e212edccab08"); // Change this
var findMultiple = true;
// ----------------------- code -----------------------
var stack = [];
db.getCollectionNames().forEach(function (collName) {
var docs = db.getCollection(collName).find();
docs.forEach(function (doc) {
doc._FROM = collName;
stack.push(doc);
});
});
while (stack.length > 0) {
var doc = stack.pop();
if (doc._id) {
if (doc._id.toString() === objectID.toString()) {
print(doc);
if (!findMultiple) {
stack = [];
}
}
}
for (var property in doc) {
var value = doc[property];
var type = Object.prototype.toString.call(value);
if (type === '[object Object]' || type === '[object Array]' || type === '[object bson_object]') {
value._FROM = doc._FROM + "/" + property;
stack.push(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment