insert a data in a array in mongodb code example

Example 1: mongodb push to arry in update

db.collection.update({_id:xx}, {$push:{letters : {$each:['first one'], $position:0}}})

Example 2: mongodb insert

db.products.insert( { item: "card", qty: 15 } )

Example 3: insert item into list mongodb

db.col.update(
    { name: 'doc', 'list.id': 2 }, 
    {$push: {'list.$.items': {id: 5, name: 'item5'}}}
)

Example 4: F# mongodb insert to array

type FriendModel = {
        Name : string
        Phone : string
    }
    type PersonModel = {
        Name : string
        Friends: FriendModel list
    }

    let insertNewFriend (personName:string) (newFriend:FriendModel) = 
        let filter = Builders.Filter.Eq((fun x -> x.Name), personName)
        let fields = StringFieldDefinition("Friends")
        let updateDefinition = Builders.Update.Push(fields,{Name="Mahdi";Phone="+1"})
        collections.UpdateOne(filter,updateDefinition)

Tags:

Misc Example