Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
How to use $pull to delete a particular data from a document in mongoDB

I'm pretty new in MongoDB,I want to delete a particular object from an array of objects in a document. I tried a lot and finds a lot of questions in StackOverflow.But none of them worked (maybe it's my fault)

following is a document from a collection that is matched by the user with userId

61f15af01a3c53dfa87e38e6

The Document

{
        "_id": "61f15af01a3c53dfa87e38ed",
        "user": "61f15af01a3c53dfa87e38e6",
        "transactions": [
            {
                "amount": 50,
                "category": "Bills",
                "type": "Expense",
                "_id": "61f15af01a3c53dfa87e38ee"
            },
            {
                "amount": 100,
                "category": "Lottery",
                "type": "Income",
                "_id": "61f15af01a3c53dfa87e38ef"
            },
            {
                "amount": 200,
                "category": "Salary",
                "type": "Income",
                "_id": "61f15af01a3c53dfa87e38f0"
            },
        ]
    }

I want to delete the transaction with an Id of 61f15af01a3c53dfa87e38ef

I tried the below one (I don't know whether it is correct)

 const  allTransactions = await Transactions.findOne({ user: req.user._id });
 const updatedTransactions = await allTransactions.update(
      {  },
      { $pull: { transactions: { id: req.params.id } } },
    );

Can anyone Spot the mistake and how can I achieve it ?

Thanks in advance :)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do it in one database call using below statement:

await Transactions.update(
    { user: "61f15af01a3c53dfa87e38e6" }, 
    { $pull: { "transactions": { _id: "61f15af01a3c53dfa87e38f0" } } } 
)

Mongo Playground

Also make sure types match. If _id is of type ObjectId instead of string you should convert req.params.id to ObjectId first. See below:

await Transactions.update(
    { user: mongoose.Types.ObjectId(req.user._id) }, 
    { $pull: { "transactions": { _id: mongoose.Types.ObjectId(req.params.id) } } } 
)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!