0

I have a mongodb collection of the form

{
  "_id":"id",
  "userEmail":"userEmailFromCustomerCollection",
  "customerFavs":[
    "www.xyz.com",
    "www.xyz.com",
    "www.xyz.com"

    ]
}

I need to add an element to the customers favs array using Jongo , I am using the following code snippet to do so .

String query = "{userEmail:'"+emailId+"'}";
    customerFavCollection.update(query).with("{$addToSet:{customerFavs:#}}", favUrl);

My problem , is that I need to upsert the document if the document does not exist already , how can I do so using Jongo, I know an easier option would be to retrieve the document by Id and if it does not exist then insert the document using save() , but I am trying to avoid the extra retrieve.

user1965449
  • 2,849
  • 6
  • 34
  • 51

1 Answers1

-1

You can add upsert() on the query.

customerFavCollection.update("userEmail:#", emailId)
                     .with("{$addToSet:{customerFavs:#}}", favUrl)
                     .upsert();
xvronny
  • 84
  • 5