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

});
});

Top comments (0)