I've a many documents like this
user:62e13ae4f9a38f7610e70bd7,
_id :62e13ae4f9a38f7610e70bdb
transactions:{
{
"amount": 50,
"category": "Bills",
"type": "Expense",
"date": "2022-01-20T00:00:00.000Z",
"_id": "62e13ae4f9a38f7610e70be0"
},
{
"amount": 100,
"category": "Lottery",
"type": "Income",
"date": "2022-01-20T00:00:00.000Z",
"_id": "62e13ae4f9a38f7610e70be1"
},
{
"amount": 200,
"category": "Salary",
"type": "Income",
"date": "2022-01-20T00:00:00.000Z",
"_id": "62e13ae4f9a38f7610e70be2"
}
}
And I want to retrieve an object from the transactions array with a particular id (I only want that object )
I tried some methods like
const transactions = await Transactions.find({
user: req.user._id,
"transactions._id": {$eq: req.params._id },
});
const transactions = await Transactions.find({
user: req.user._id,
"transactions": { _id: req.params._id },
});
const transactions = await Transactions.find({
user: req.user._id,
"transactions": { $elemMatch:{_id: req.params._id }},
});
but nothing seems to be working, can anyone help me to solve this And please mention the mistake I made.
CodePudding user response:
Try to match the transactions._id
directly:
"transactions._id": req.params._id
Example
const transactions = await Transactions.find({
user: req.user._id,
"transactions._id": req.params._id
});
Update
From the comment, it's possible to use projection as the second parameter of .find()
to return only the object it found in the transactions
.
const transactions = await Transactions.find({
user: req.user._id,
"transactions._id": req.params._id
}, { "transactions.$": 1 });
CodePudding user response:
If you only want that matching element, you have to use aggreation.
db.collection.aggregate([
{
$unwind: "$transactions"
},
{
$match: {
"transactions.id": "idGoesHere"
}
}
])
As you commented in the other answer, you could use positional
operator to project the matching elements as well.