1

Suppose I have the following document:

{
_id: "609bcd3160653e022a6d0fd8",
companies:{
   apple: [
       {
        product_id: "609bcd3160653e022a6d0fd7"
       },
       {
        product_id: "609bcd3160653e022a6d0fd6"
       }
   ],
   microsoft: [
       {
        product_id: "609bcd3160653e022a6d0fd5"
       },
       {
        product_id: "609bcd3160653e022a6d0fd4"
       }
   ]
  }
}

How can I find and delete the object with the product_id: "609bcd3160653e022a6d0fd4".

P.S: I use MongoDB native driver for Nodejs.

Thanks a lot!

turivishal
  • 34,368
  • 7
  • 36
  • 59
Maor agai
  • 221
  • 1
  • 3
  • 11
  • See [MongoDB, remove object from array](https://stackoverflow.com/questions/15641492/mongodb-remove-object-from-array), you can use `findOneAndUpdate` method. – turivishal May 12 '21 at 14:27
  • @turivishal - But if I don't know the name of the array? I want to find the object by product_id, but I don't know the name of the array. – Maor agai May 12 '21 at 14:31

1 Answers1

0

If I don't know the name of the array? I want to find the object by product_id

It is not possible with regular update query, you can try update with aggregation pipeline starting from MongoDB 4.2,

  • $objectToArray convert companies object to array in key-value format
  • $map to iterate loop of above converted array
  • $filter to filter dynamic array's by product_id
  • $arrayToObject convert key-value array to regular object format
let product_id = "609bcd3160653e022a6d0fd4";
YourSchema.findOneAndUpdate(
  { _id: "609bcd3160653e022a6d0fd8" }, // put your query
  [{
    $set: {
      companies: {
        $arrayToObject: {
          $map: {
            input: { $objectToArray: "$companies" },
            in: {
              k: "$$this.k",
              v: {
                $filter: {
                  input: "$$this.v",
                  cond: { $ne: ["$$this.product_id", product_id] }
                }
              }
            }
          }
        }
      }
    }
  }],
  {    
    new: true // return updated document
  }
);

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59