Home > Net >  How can I get only specific object from nested array mongodb
How can I get only specific object from nested array mongodb

Time:08-11

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
 }
]
}

CodePudding user response:

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
}
  • Related