I have a collection with documents with the following structure:
{
"_id": ObjectId("..."),
"rides": [
{
status_history: ["status1", "status2", "status3"]
},
{
status_history: ["status4", "status5"]
}
...
]
}
What I want to do is append a new status to the status_history array of the the last ride in the rides array, achieving something like:
{
"_id": ObjectId("..."),
"rides": [
{
status_history: ["status1", "status2", "status3"]
},
{
status_history: ["status4", "status5", "NEW_STATUS_HERE"]
}
...
]
}
But I can't quite figure out how to do that. I'm using the mongo-driver package to connect to the db.
Here's the code I managed to come up with:
filter := bson.M{"_id": objectId}
arrayFilters := options.ArrayFilters{
Filters: bson.A{
bson.M{"s": bson.M{"rides": bson.A{"$slice", -1}}},
},
}
upsert := true
opts := options.UpdateOptions{
ArrayFilters: &arrayFilters,
Upsert: &upsert,
}
update := bson.M{
"$push": bson.M{
"rides.$[s].status_history": statusEntry,
},
}
result, err := col.UpdateOne(ctx, filter, update, &opts)
fmt.Println(fmt.Sprintf(
"Matched %v, Modified %v, Upserted %v",
result.MatchedCount,
result.ModifiedCount,
result.UpsertedCount,
))
The output of that Println is Matched 1, Modified 0, Upserted 0. Indeed, inspecting the item in the collection shows that it is unchanged.
What exactly am I getting wrong here?
status_historyarray do you want to update (or add a new status to) - supposing if there are 10 of them?ridesarray will always have exactly onestatus_historyarray. So what I want is to append a new status to the onestatus_historyarray inside the last object in theridesarray.