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?