简体   繁体   中英

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 )

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": 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 });

More information

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM