Home > Blockchain >  Find a object inside a document by a field and retrive the object in MongoDB
Find a object inside a document by a field and retrive the object in MongoDB

Time:03-22

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 bellow.

enter image description here

I tried:

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

Didn't work. Never worked with these kinds of DB and am a bit lost. Any help is appreciated.

CodePudding user response:

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.

  • Related