0

These are my Mongodb document structs.

type Company struct {
Id              bson.ObjectId `bson:"_id,omitempty"`
Company_name    string
Admin           UserMinimal
Process         []ProcessItem
}

type ProcessItemMinimal  struct {
Id              bson.ObjectId `bson:"_id,omitempty"`
Process_name    string
Processtype     int64   
}

type ProcessItem  struct{
ProcessItemMinimal  `bson:",inline"`
Sortorder           int64   
}

This is my mongodb document.

{
    "_id" : ObjectId("56cd99109096f3b762f4f149"),
    "company_name" : "xyz",
    "admin" : {
        "email" : "kk@kk.kk",
        "fullname" : "kk"
    },
    "process" : [ 
        {
            "process_name" : "Enquiry",
            "processtype" : NumberLong(0),
            "sortorder" : NumberLong(0)
        }, 
        {
            "process_name" : "Converted",
            "processtype" : NumberLong(1),
            "sortorder" : NumberLong(1)
        }, 
        {
            "process_name" : "MileStone 1",
            "processtype" : NumberLong(1),
            "sortorder" : NumberLong(2)
        }
    ]
}

I need to add one more "process" to process array. Is it possible? If yes, how can I query that in mgo?

Arjun Ajith
  • 1,850
  • 5
  • 21
  • 46

1 Answers1

2

To insert another document to the array use $push

In mgo,

// Create the new 'ProcessItem' document you want to insert.
newProcess := ProcessItem {
    ProcessItemMinimal : processItem,
    SortOrder          : sortOrder
}

change := bson.M {
    "$push": bson.M {
        "process": newProcess,
    },
}

// Update the necessary 'Company' document
companyCollection.UpdateId(company.ID, change)
Aruna Herath
  • 6,241
  • 1
  • 40
  • 59
  • 1
    Thanks bro.. needed to add "$push": bson.M {"process": newProcess[0].ProcessItemMinimal } otherwise the newly added data will become another array.. thanks very much – Arjun Ajith Feb 25 '16 at 11:26