Search This Blog

2024/04/24

MongoDb Interview Question:Insert into leaf node in nexted array

 Assume there is a document with nested arrays that looks like the one below. How

can you insert a “room” that has the name “Room 44” and size of “50” for a
particular “house” that belongs to this user?

db.users.insertOne({
"_id": "682263",
"userName" : "sherif",
"email": "sharief@aucegypt.edu",
"password": "67834783ujk",
"houses": [
{
"_id": "2178123",
"name": "New Mansion",
"rooms": [
{
"name": "4th bedroom",
"size": "12"
},
{
"name": "kitchen",
"size": "100"
}
]
}
]
})

Answer:
db.users.updateOne(
{ "_id": "682263","houses._id":"2178123"},
{ "$push":
{"houses.$.rooms":
{
"name": "Room 44",
"size": "50"
}
}
}
)

No comments:

Post a Comment