[英]Get an element from an array of objects with an id in mongodb using nodejs and mongoose
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 )我想从具有特定 id 的事务数组中检索一个 object (我只想要那个 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.但似乎没有任何效果,任何人都可以帮我解决这个问题并请提及我犯的错误。
Try to match the transactions._id
directly:尝试直接匹配transactions._id
:
"transactions._id": req.params._id
const transactions = await Transactions.find({
user: req.user._id,
"transactions._id": req.params._id
});
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
.从评论中,可以使用投影作为.find()
的第二个参数来仅返回它在transactions
中找到的 object 。
const transactions = await Transactions.find({
user: req.user._id,
"transactions._id": req.params._id
}, { "transactions.$": 1 });
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.正如您在另一个答案中评论的那样,您也可以使用positional
运算符来投影匹配的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.