Upsert Document with increment in nested array

I have a collection that keeps track of the number of visits a tour (identified by tourID). This is the schema:

    agencyID: { type: Number },
    tourID: { type: Number, unique: true },
    totalVisits: Number,
    hosts: [
      {
        name: {type: String},
        total: {type: Number}
      }
    ]

Given an object like this:

   agencyID: 123,
   tourID: 9,
   hostName: "www.google.com"

I’m trying to increment the totalVisits field if the tours exists, or create a tour with totalVisits = 1 in the same query (upsert). I’ve been able to do this without a problem. This should be the result:

    agencyID: 123,
    tourID: 9,
    totalVisits: 1,
    hosts: [
      {
        name: "www.google.com",
        total: 1
      }
    ]

However, I also want to do an upsert in the nested array, that has objects identified by name. If the host (in this case www.google.com exists, we should increment the total value of this host. If the host does not exist, then it should push a new object to the array. If now we receive this data, for example,

   agencyID: 123,
   tourID: 9,
   hostName: "www.mongodb.com"

The result should be this:

    agencyID: 123,
    tourID: 9,
    totalVisits: 2,
    hosts: [
      {
        name: "www.google.com",
        total: 1
      },
      {
        name: "www.mongodb.com",
        total: 1
      }
    ]

I haven’t been able to find any way to make this second upsert in the nested array.
Any help?

That’s a bit trickier but you can do that using aggregation expressions with expressive update.

I don’t think there’s an example in the docs for exactly this but you can see some code that does this in a Jira ticket comment here: https://jira.mongodb.org/browse/SERVER-1050?focusedCommentId=2305623&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-2305623 - in the forums there are a few examples that are similar, just search for the words upsert and $concatArrays

Asya