Aybuke
Aybuke

Reputation: 211

MongoDB JsonObject and JsonArray

I'm new MongoDB. I have a collection is named "surveyCollection". I insert some data to collection with shell,

db.surveyCollection.insert({
   "count":30, 
   "people": [
        {
           "firstName":"John",
           "lastName":"Jason"
        }
   ]
})
db.surveyCollection.insert({
   "count":30, 
   "people": [
        {
           "firstName":"Sarah",
           "lastName":"Smith"
        }
   ]
})

And I have data below ( db.surveyCollection.find().pretty());

{
    "_id" : ObjectId("5873d0c86c3319a579754d00"),
    "count" : 30,
    "people" : [
        {
            "firstName" : "John",
            "lastName" : "Jason"
        }
    ]
}
{
    "_id" : ObjectId("5873d0c86c3319a579754d00"),
    "count" : 30,
    "people" : [
        {
            "firstName" : "Sarah",
            "lastName" : "Smith"
        }
    ]
}

I don't know how can I insert a new people to any survey. I mean, I want to have datas like below;

{
    "_id" : ObjectId("5873d0c86c3319a579754d00"),
    "count" : 30,
    "people" : [
        {
            "firstName" : "John",
            "lastName" : "Jason"
        }
    ]
}
{
    "_id" : ObjectId("5873d0c86c3319a579754d00"),
    "count" : 30,
    "people" : [
        {
            "firstName" : "Sarah",
            "lastName" : "Smith"
        },
        {
            "firstName" : "George",
            "lastName" : "Smith"
        }
    ]
}

I mean, how can I reach values in JsonArray?

Thank you

Upvotes: 1

Views: 2539

Answers (1)

Supradeep
Supradeep

Reputation: 3266

Use $push method to push an item into array of a document as shown below :

db.surveyCollection.update(
 { "_id" : ObjectId("5873d0c86c3319a579754d00") },
 { $push: { people: { "firstName" : "George", "lastName" : "Smith"} } }
) 

This will add the object { "firstName" : "George", "lastName" : "Smith"} to the array people in the document of {"_id" : ObjectId("5873d0c86c3319a579754d00")}

Upvotes: 2

Related Questions