DEV Community

Vimal
Vimal

Posted on

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

});
});

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay