Home:ALL Converter>MongoDB query an array of documents for specific match

MongoDB query an array of documents for specific match

Ask Time:2022-04-06T23:34:45         Author:lordZ3d

Json Formatter

I want to search the transactions array looking for a specific match. In this example, by pipedrive_id.

enter image description here

This is what I tried (as per mongodb instructions and this other stack overflow post)

const pipedrive_id = 1677;
const inner_pipedrive_id = 1838;

const result = await Transactions.find({
    pipedrive_id,
    'transactions': { $elemMatch: { 'pipedrive_id': inner_pipedrive_id } }
});

const result2= await Transactions.find({
    'transactions': { $elemMatch: { 'pipedrive_id': inner_pipedrive_id } }
});

const result3 = await Transactions.find({
    'transactions.pipedrive_id': inner_pipedrive_id
});

And each result itteration returns all transaction items (all 6 items, instead of 2 [that's how many Mark Smith has in the array).

Author:lordZ3d,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71769658/mongodb-query-an-array-of-documents-for-specific-match
Shivam :

You can use aggregate to filter out the array. Something like this\nYou can remove $project if you want all the fields\ndb.collection.aggregate([\n {\n $match: {\n pipedrive_id: "1677"\n }\n },\n {\n $unwind: "$transactions"\n },\n {\n $match: {\n "transactions.pipedrive_id": "1838"\n }\n },\n {\n $project: {\n _id: 0,\n pipedrive_id: 1,\n transactions: 1\n }\n }\n])\n\nYou can check the Mongo playground here.",
2022-04-06T16:04:03
yy