MongoDB - How to find ONLY embedded documents that have field value that matche a given value

30 Views Asked by At

This is the structure of a document in my collection where the data is grouped by report week (i.e., all the data for the different currencies released in the same week's report are grouped together)

{
    "_id": {
      "$oid": id
    },
    "year": 2024,
    "week": "Report Week 04",
    "data": [
        {
            "date": "Jan 23 2024",
            "reportWeek": "Report Week 04",
            "currencyName": "CANADIAN DOLLAR",
            "marketCode": "090741",
            some more fields...
        },
        some more documents...
    ]
}

The collection.data field is an embedded array of documents from which I would like to find only the documents whose marketCode field value matches a given parameter.

Based off the MongoDB documentation (Specify a Query Condition on a Field in an Array of Documents), I came up with this:


const dataColl = client.db('database').collection('collection');

    const data = await dataColl.find({

        'data.marketCode': marketCode  // marketCode is a string argument that is passed to the function.

        // I also tried this 'data.marketCode': { $eq: marketCode }

    }).project({projections...}).toArray();

I expected that this query will go to all documents in the collection and get every embedded document that has data.marketCode === marketCode. However, it just returns the full collection with all the data (albeit with the projections correctly applied).

I need help figuring out the correct find command to use.

P.S: data.marketCode values are stored as strings in the database

0

There are 0 best solutions below