To perform aggregation in MongoDB to find an array within an array, you can use the $unwind, $match, and $group stages to accomplish this task. Assuming you have a collection named collectionName with documents containing nested arrays, here's how you can perform the aggregation in Node.js:

const { MongoClient } = require('mongodb'); async function findArrayInArray() { const uri = 'mongodb://localhost:27017'; // Replace with your MongoDB connection string const client = new MongoClient(uri); try { await client.connect(); const database = client.db('yourDatabaseName'); // Replace 'yourDatabaseName' with your actual database name const collection = database.collection('collectionName'); const pipeline = [ { $unwind: '$outerArray' }, // Unwind the outer array { $unwind: '$outerArray.innerArray' }, // Unwind the inner array { $match: { 'outerArray.innerArray': 'searchValue', // Replace 'searchValue' with the value you are searching for in the inner array }, }, { $group: { _id: '$_id', matchedDocument: { $first: '$$ROOT' }, // Preserve the original document }, }, { $group: { _id: null, matchedDocuments: { $push: '$matchedDocument' }, // Collect all matched documents in an array }, }, ]; const result = await collection.aggregate(pipeline).toArray(); console.log(result); } catch (err) { console.error('Error:', err); } finally { client.close(); } } findArrayInArray();

In this example, we use the $unwind stage twice to flatten the nested arrays, then we apply the $match stage to find the documents that contain the desired value in the inner array. Finally, we use the $group stage to group the matched documents back together, creating an array of matched documents.

Remember to replace 'yourDatabaseName', 'collectionName', and 'searchValue' with your actual database name, collection name, and the value you are searching for in the inner array, respectively.

Note: Aggregation can be resource-intensive, especially for large datasets. Be cautious when using aggregation pipelines and ensure that you have appropriate indexes on the fields being used in the pipeline stages to optimize performance.

Have questions or queries?
Get in Touch