0

Please I am new in mongo db and I want to delete one item from my list, I tried several approches but it's not working.

{

name: 'ABCDE',

snapshotString: [
        '{"timestamp":1589316266621,"testObject":{}, "moreAttributes" : "XXXXX"}',
        '{"timestamp":1589316279337,"testObject":{}, "moreAttributes" : "XXXXX"}'
],
snapshots: [
   1589316266621,
    1589316279337
]
}

I want to delete a snapshotString for given timestamp I did this:

this.testCase.updateOne(
                {name:room, "snapshotString.timestamp": timestamp}, 
                { $pull: { "snapshotString.timestamp": timestamp } }, { safe: true }, 
                function(err, obj) {
                    console.log(" ***** err ***** "+err);
        });

And it's a way to have one query to delete both documents with timestamp in snapshotString and snapshots in the same query?

Thanks

Jens
  • 5,767
  • 5
  • 54
  • 69
Nissan
  • 3
  • 1
  • Does this answer your question ? https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb – whoami - fakeFaceTrueSoul May 12 '20 at 21:56
  • In that example `snapshotString` contains an array of strings, not an array of objects. Strings don't have fields, so you can't query `snapshotString.timestamp` - it will never match anything. You might try a regular expression for that match. – Joe May 12 '20 at 22:05
  • @whoami unfortunately not. – Nissan May 13 '20 at 01:41

1 Answers1

1

You can try the below:

this.testCase.updateOne(
    {name: room},
    {$pull:
        {snapshotString:
            {$regex: timestamp}
        }
    });

Note: I am assuming here, timestamp is a string, if not, then you should convert it to string, as $regex operator will accept only string.

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30