I've been desperate for a few days now that I'm looking for a way to update an object that is inside an array Here is a short excerpt from my code
{
"_id": {
"$oid": "62684e70e89eca781cc4f384"
},
"user": "ronen",
"roles": {
"User": 2001,
"Editor": 1984,
"Admin": 5150
},
"password": "$2b$10$pO52RJD0zgFHDW6BBCo5iu3A5Lx0TCbCbzgjvc3FxxQZGUjblSPaK",
"Stock": [
{
"sku": "777",
"productname": "rone4n",
"sendout": 5,
"recived": 3,
"totalinstock": 55,
"location": "A770770",
"_id": {
"$oid": "626a9bb384cd350c6e784794"
}
},
{
"sku": "ex77xee",
"productname": "ron",
"sendout": 43,
"recived": 34,
"totalinstock": 444,
"location": "fff",
"_id": {
"$oid": "626adab728fcc6005453a481"
}
}
],
}
I want to return the only where "sku": "ex77xee" icant undersdet how to search object in array
{
"sku": "ex77xee",
"productname": "ron",
"sendout": 43,
"recived": 34,
"totalinstock": 444,
"location": "fff",
"_id": {
"$oid": "626adab728fcc6005453a481"
}
I prefer to do this on the MongoDB side, i try with findONe but i unsuccess
CodePudding user response:
You can run this query, You can read more about $elemMatch here
db.collection.find({
stock: {
$elemMatch: {
sku: "ex77xee"
}
}
},
{
"stock.$": 1,
"user": 1, //<-- You can remove this, if you don't want these values
"roles": 1, //<-- You can remove this, if you don't want these values
"password": 1 //<-- You can remove this, if you don't want these values
})
You can check mongo playground here
$elemMatch
is very versatile, you can add more conditions to filter later on if needed