skip to Main Content

So what I’m trying to do, if you take a look at the picture bellow, is to delete just one document inside transactions by it’s id.

enter image description here

What I have tried:

const result = await db.updateMany({ pipedrive_id: 999 }, { $pull: { transactions: { id: id } } });

As suggested in this stackoverflow post. But it didn’t do anything.

Then I tried:

const result = await db.findOneAndDelete(
  {
    'transactions._id': { $in: id },
  }
);

Where id in both cases is the _id of the transaction inside transactions. But this didn’t work as expected as it deleted everything all items in the collection and the parent as well.

So I’m kinda stuck, any help?

2

Answers


  1. Chosen as BEST ANSWER

    So, I kinda achieved my goal, but I'm betting there's proper mongodb solution to this. This is just hacky way to do it I guess.

    // fetch all documents inside transactions collection
    const queryResult = await db.find({ pipedrive_id: 999 });
    const idToRemove = 'some id';
    
    if (queryResult.length) {
    // filter out the ID's that needs to be deleted
    const results = queryResult.transactions.filter((item) => idToRemove !== item['id']);
    
    // update the document with the filtered ones (aka deleting the specified ones)
    await db.updateOne(
      {
        pipedrive_id: 999
      },
      {
        $set: { transactions: results },
      }
    )
    

  2. The problem is the answer you are trying to follow doesn’t works. (Also the comment in the answer is correct). Check this example and how it fails.

    As explained, for example in the Node.JS Driver Jira Ticket $pull operator doesn’t work with dot notation

    this is expected behavior, and simply is not currently supported by the query language.

    So you need this query:

    db.updateOne({
      "_id": 1,
      "transactions._id": 1
    },
    {
      "$pull": {
        "transactions": {
          "_id": 1
        }
      }
    })
    

    Note how in the $pull object there is not dot notation, is defined the object itself.

    Example here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search