Golang mgo append to a nested array in a document
Small tutorial on how to add/push/append a new element to an array/list inside a document, based on my previous post.
Lets say we have a collection called 'users' that contains the data of our users, and in each user document there is a nested array that keeps track of the login attempts, the document of user 'John' looks like this:
[
{
"_id": "57437f271e02f4bae78788af",
"firstname": "John",
"lastname": "doe",
"email": "johndoe@gmail.com",
"password": "somehashedpassword",
"loginattempts": [
{
"timestamp": 1464042139,
"ip": "192.168.0.2"
},
{
"timestamp": 1464040000,
"ip": "192.168.0.5"
},
{
"timestamp": 1464000139,
"ip": "127.0.0.1"
}
]
}
]
Add a new login attempt
Someone attempts to login on Johns account, and you want to log this by adding a new attempt under the nested "loginattemtps".
Who := bson.M{"_id" : "57437f271e02f4bae78788af"}
PushToArray := bson.M{"$push": bson.M{"loginattempts": bson.M{"timestamp": 1464045212, "ip": "195.0.0.200"}}}
collection.Update(Who, PushToArray)
We use 'Update()' here, that takes two arguments, the first one is a interface to select which document, this is equal to 'Find()'. And a second argument that is an interface to update the selected document.
In our case we select John's document by looking him up with his '_id'.
And then we add to the array with the MongoDB '$push' operator. Read it like this:
Push to array 'loginattempts' -> timestamp = 1464045212 AND ip = 195.0.0.200