Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongodb query to find an object from an array

I have following data in my mongodb database , how can I write a mongoose query to select a particular object from "cartItems" which is a array of objects and update its "qty" and "price" filed.

Here’s the data:-

{
  _id: new ObjectId("634a67e2953469f7249c9a7f"),
  user: new ObjectId("6348a56590b49a8313d434fa"),
  cartItems: [
    {
      _id: new ObjectId("63494302fc6db508894ba109"),
      name: 'Chola Bhatura',
      image: 'https://www.indianhealthyrecipes.com/wp-content/uploads/2022/03/bhatura-recipe-680x1020.jpg.webp',
      qty: 1,
      price: 200
    },
    {
      _id: new ObjectId("634941f3fc6db508894ba105"),
      name: 'Poha',
      image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSuxnPaCuwhqgfnK3DfXFGelvKpfhjyDWpmkQ&usqp=CAU',
      qty: 1,
      price: 50
    }
  ],
  totalQty: 2,
  totalPrice: 250,
  createdAt: 2022-10-15T07:57:22.941Z,
  updatedAt: 2022-10-15T09:57:29.734Z,
  __v: 0
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it with positional operator – $, like this:

db.collection.update({
  _id: ObjectId("634a67e2953469f7249c9a7f"),
  "cartItems._id": ObjectId("634941f3fc6db508894ba105")
},
{
  "$set": {
    "cartItems.$.qty": 10,
    "cartItems.$.price": 100
  }
})

Working example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading