I want to search the transactions
array looking for a specific match. In this example, by pipedrive_id
.
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).
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