I'm using MongoDb 8.0.4 and Mongosh 2.3.8.
After creating a collection with the following code, I'd like to update the array of Residents within a House document. The House documents are also in an array of their parent document (Suburb).
db.Suburbs.insertOne({
_id: new ObjectId("000000000000000000001001"),
Location: "Virginia",
SuburbName: "Tanglewood",
Houses: [
{
_id: new ObjectId("000000000000000000002001"),
Address: "Mayberry Ln",
NumFloors: 2,
Residents: ["Harry", "Sally", "Junior"]
},
{
_id: new ObjectId("000000000000000000002002"),
Address: "Center St",
NumFloors: 1,
Residents: ["Johnny", "Corin", "Simmy"]
},
{
_id: new ObjectId("000000000000000000002003"),
Address: "Tinsletown",
NumFloors: 3,
Residents: ["Rufus", "Betty"]
}
]})
The goal is two-fold. To pull or add a Resident from the array of Residents.
The following code I used to modify a value at the same level of Residents, but I don't know how to target the values within the Residents array.
db.Suburbs.findOneAndUpdate(
{"_id": ObjectId("000000000000000000001001")},
{
$set: { "Houses.$[myIdentifier].NumFloors": 4}
},
{
arrayFilters: [ {"myIdentifier._id": ObjectId("000000000000000000002002")} ]
}
);