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.
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:
- Find the document based on "transaction.created".
- Project only the matching "transaction.created" object.
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:
- Find the document based on transaction.created
- Filter only the matched transaction created object.
For best performance index need to be created on the "transaction.created" field.