0

I've got a document in a collection 'events' with the following structure:

{ 
  "_id" : "abc",
  "text" : "some text",
}

I wish to update the document by inserting an array named guestOwner. The result I want would update the document like this:

{ 
  "_id" : "abc",
  "text" : "some text",
  "guestOwner" : [
    {
        "name" : "JACK BLACK", 
        "guests" : [
            "GUEST1",
            "GUEST2"
        ]
    }
  ]
}

So I tried an mongo update with the following:

db.events.update({ _id: eventid }, { $push: { guestOwner: { name: username, guests: allGuests } } });

where 'username' is a string, and 'allGuests' is an array of names ["Guest1", "Guest2"]

The issue for me is when a subsequent update to the document occurs, I would want to push a the new 'allGuests' array into the existing one if the name is the same. For example, if a second update occurs with 'allGuests' = ["GUEST3"], and with the same name = "JACK BLACK", I would want the document to be:

{ 
  "_id" : "abc",
  "text" : "some text",
  "guestOwner" : [
    {
        "name" : "JACK BLACK", 
        "guests" : [
            "GUEST1",
            "GUEST2"
            "GUEST3"
        ]
    }
  ]
}

BUT, if the document were updated with a different name = 'JOHN SMITH' where allGuests array = ["GUEST3"], it would create:

{ 
  "_id" : "abc",
  "text" : "some text",
  "guestOwner" : [
    {
        "name" : "JACK BLACK", 
        "guests" : [
            "GUEST1",
            "GUEST2"
        ]
    },
    {
        "name" : "JOHN SMITH", 
        "guests" : [
            "GUEST3"
        ]
    }
  ]
}

Would I need conditional statements surrounding the mongo update to check for guestOwner[0].name? Not sure if mongo could do this on its own, or if a bunch of logic is going to be necessary.

0

1 Answer 1

2

You could simply do an update where in the query section you would specify the name:

db.events.update({
  "_id" : ObjectId("someId"), "guestOwner.name": "JACK BLACK"}, {
  $push: { "guestOwner.$.guests": "GUEST11" // etc }
})

If this returns the number of updated elements to be 1 you are good to go since the name exists etc.

If it returns 0 then that name does not exists so you can run:

db.events.update({"_id" : ObjectId("someId")}, {
  $addToSet: { guestOwner: { name: "JACK BLACK" // etc }}
})

It would save you one call since if you have to check if the record exists you would always do 2 rounds. One to check and another to take action based on the result. Here if the records is already there you only do one update.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yes. Makes perfect sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.