Find data from MongoDB db through all collection and documents with help of map

vimal_adithan

Vimal

Posted on March 14, 2024

Find data from MongoDB db through all collection and documents with help of map

const MongoClient = require('mongodb').MongoClient;

// Connection URI
const uri = 'mongodb://localhost:27017';

// Database Name
const dbName = 'your_database_name';

// Connect to the MongoDB server
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}

console.log('Connected to MongoDB server');

// Select the database
const db = client.db(dbName);

// Use the aggregation pipeline to search for the document with name equal to 'john' across all collections
db.aggregate([
// For each collection in the database
{ $listCollections: {} },
{ $toArray: {} },
{ $map: {
input: "$$ROOT",
as: "collection",
in: {
$unionWith: {
coll: "$$collection.name",
pipeline: [
{ $match: { name: "john" } }
]
}
}
}
},
// Flatten the array of arrays into a single array
{ $unwind: "$collection" },
// Replace null values with empty arrays
{ $replaceRoot: { newRoot: { $ifNull: ["$collection", []] } } }
]).toArray((err, result) => {
if (err) {
console.error('Error searching for document:', err);
return;
}

console.log('Found documents:', result);

// Close the connection
client.close();
Enter fullscreen mode Exit fullscreen mode

});
});

💖 💪 🙅 🚩
vimal_adithan
Vimal

Posted on March 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024