1

I'm working in a project oj NodeJS, and I want to delete an element of array containing objets.

The Schema is:

{
  "products" : [
    {
      "productid" : 1,
      "name" : "product 1",
      "price" : 200
      
    },
    {
      "productid" : 2,
      "name" : "product 2",
      "price" : 300
      
    },
    {
      "productid" : 3,
      "name" : "product 3",
      "price" : 350
      
    },
    {
      "productid" : 4,
      "name" : "product 4",
      "price" : 300
      
    },
,
    {
      "productid" : 5,
      "name" : "product 5",
      "price" : 300
      
    }
    
  ]
}

And i want to delete product 3, how is query in mongodb? the "productid" attribute is key, does not repeat it

Thanks.

2 Answers 2

1

Use this:

Change collection name and {} as per your need.

db.collection.update( {}, { "$pull" : { "products" : { "productid" : 3 } } });

if it matches multiple element then use multi option like

db.collection.update( {}, { "$pull" : { "products" : { "productid" : 3 } } }, 
{ multi: true });
Sign up to request clarification or add additional context in comments.

Comments

0
db.collection.update( {<query>}, { "$pull" : { "products.productid" : 3  } });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.