0

If i have a Person collection that has many addresses, how can I insert multiple addresses that belong to a person? I know how to do it if it were a one to one relationship where I would simply do something like:

db.persons.update({_id: '12345'}, {$set: {'address': '12345 fake st'}})

However, that won't work for a one to many relationship since the person's address would get replaced every time someone adds an address to that person. Can someone help? Thank you in advance.

Juan Carlos Farah
  • 3,709
  • 31
  • 40
Trung Tran
  • 11,579
  • 39
  • 105
  • 187

1 Answers1

1

If you want a person to hold many addresses then you could make address an array and you could insert new addresses using the push operator.

db.persons.update(
    { "_id": "12345" }, 
    { "$push": { "address": "12345 fake st"}}
);

Your schema would then look like this:

{
    "_id" : "12345",
    "address" : [
        "12345 fake st",
        "6789 second st",
        ...
    ]
}

Of course you can make this as complex as required. So if you need to store extra information for each address, you can instead insert subdocuments into the address array.

{
    "_id" : "12345",
    "address" : [
        {
            "number" : "6789",
            "street" : "second st",
            "primary" : false
        },
        {
            "number" : "12345",
            "street" : "fake st",
            "primary" : true
        },
        ...
    ]
}

As noted in the comments, if you want to ensure that there are no duplicates in your array, you should use the $addToSet operator, which provides that functionality.

Juan Carlos Farah
  • 3,709
  • 31
  • 40
  • thanks - i was just doing some more research on this and is this any different or does it have any advantages over using the $addToSet operator? – Trung Tran Apr 09 '15 at 01:36
  • The `$addToSet` operator ensures that there are no duplicates in the array. In your case, it would make sense to use `$addToSet`, unless you want duplicates. I have noted that in the answer to be clear. – Juan Carlos Farah Apr 09 '15 at 01:40