Home > OS >  mongodb query to find an object from an array
mongodb query to find an object from an array

Time:10-15

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
}

CodePudding user response:

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

  • Related