2

I'm using mongoDB with PHP. I know how to get the document based on product_id, but I need only a specific object from the whole document, I don't know how to get only specific object from nested array based on product_id.

for ex. My expected output is:

products": [
  {
    "product_id": 547,
    "name": "cola",
    "quantity": 24
  }
]

then make some changes on object p.s update the quantity then update it to the database.

My collection looks like

"_id": {
 "$oid": "62ed30855836b16fd38a00b9"
},
"name": "drink",
"products": [
 {
   "product_id": 547,
   "name": "cola",
   "quantity": 24
 },
 {
   "product_id": 984,
   "name": "fanta",
   "quantity": 42
 },
 {
   "product_id": 404,
   "name": "sprite",
   "quantity": 12
 },
 {
   "product_id": 854,
   "name": "water",
   "quantity": 35
 }
]
}

1 Answer 1

1

Try this:

db.getCollection('test').aggregate([
    {
        "$unwind": "$products"
    },
    {
        "$match": {
            "products.product_id": 547
        }
    },
    {
        "$replaceRoot": {
            "newRoot": {
                "$mergeObjects": [
                    "$$ROOT",
                    "$products"
                ]
            }
        }
    },
    {
        "$project": {
            "products": 0
        }
    }
])

The query gives the following output:

{
    "name" : "cola",
    "product_id" : 547,
    "quantity" : 24
}
Sign up to request clarification or add additional context in comments.

3 Comments

works perfect. Can you help me how can I update on this same way p.s update quantity of product and update only this object
You need to add $set as the last stage of your aggregate.
I'm trying to update with same query but the last stage as '$set' => ['products' => $to_update_array] but doesn't work, can you correct me ? @sudhanva

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.