Search code examples
node.jsmongodb

Find a object inside a document by a field and retrieve the object in MongoDB


So I'm using NodeJS to query MongoDB (4.4). I'm trying to figure how to search for a field inside an object inside a document and retrieve the object (or at least the _id). The field I'm querying by is the created field within the transactions document. How the table looks like is below.

enter image description here

I tried:

const result = await Model.findOne({}, { created: createdDate });

This didn't work. I've never worked with these kinds of DB and am a bit lost. What can I try next?


Solution

  • Maybe something like this:

    Option 1: ( Find )

    db.collection.find({
      "transactions.created": "2022-12-21"
    },
    {
       transactions: {
          $elemMatch: {
            created: "2022-12-21"
          }
       }
    })
    

    Explained:

    1. Find the document based on "transaction.created".
    2. Project only the matching "transaction.created" object.

    playground1

    Option 2: (Aggregation)

    db.collection.aggregate([
    {
      $match: {
        "transactions.created": "2022-12-21"
      }
    },
    {
      $addFields: {
        transactions: {
         "$filter": {
           "input": "$transactions",
           "as": "t",
           "cond": {
             $eq: [
               "$$t.created",
               "2022-12-21"
             ]
            }
          }
         }
       }
      }
    ])
    

    Explained:

    1. Find the document based on transaction.created
    2. Filter only the matched transaction created object.

    playground2

    For best performance index need to be created on the "transaction.created" field.