how to insert new data in an embedded document in

2019-09-09 09:42发布

问题:

I have a document about employees of a company and each employee has multiple addresses. It is an embedded document

{
   _id: 12,
   emp_name: "Joy Pett",
   emp_gender: "Male",
   emp_address: [
                  {
                  street: "123 Fake Street",
                  city: "Faketon",
                  state: "MA",
                  },
                  {
                  street: "1 Some Other Street",
                  city: "Boston",
                  state: "MA",
                  }
              ]
}

Now I want to insert a new address for this employee. What is the query to insert new address for this employee??

回答1:

What is want is update your document. You need to use the update() method and the $push operator which appends a specified value to an array.

Demo

Document before update operation.

{ 
        "_id" : 12,
        "emp_name" : "Joy Pett",
        "emp_gender" : "Male",
        "emp_address" : [
                {
                        "street" : "123 Fake Street",
                        "city" : "Faketon",
                        "state" : "MA"
                },
                {
                        "street" : "1 Some Other Street",
                        "city" : "Boston",
                        "state" : "MA"
                }
        ]
}

Now let push the following address to the "emp_address":

{
    street: "125 Fake2 Street2",
    city: "Faketon2",
    state: "SA"
}

Our query:

db.collection.update({ '_id': 12 }, 
    { '$push': { 
        'emp_address': {
            street: "125 Fake2 Street2",
            city: "Faketon2",
            state: "SA"
        }
    }}
)

After our update operation.

{
        "_id" : 12,
        "emp_name" : "Joy Pett",
        "emp_gender" : "Male",
        "emp_address" : [
                {
                        "street" : "123 Fake Street",
                        "city" : "Faketon",
                        "state" : "MA"
                },
                {
                        "street" : "1 Some Other Street",
                        "city" : "Boston",
                        "state" : "MA"
                },
                {
                        "street" : "125 Fake2 Street2",
                        "city" : "Faketon2",
                        "state" : "SA"
                }
        ]
}

You can also use the $addToSet to avoid duplicate address in the array.