Saturday, January 21, 2017

upsert - update if that value is not present in the collection

sample:

db.pageviews.update({_id:"/sports/foodball"},{$inc:{views:1}},true)

Eg:

Suppose we have documents in the users collection of the form:

{
    _id : "Jane",
    likes : [ "tennis", "golf" ]
}

How would we, in the mongo shell, add that this user likes "football"? We want to record this even if the user does not yet have a document. We also want to avoid having duplicate items in the "likes" field.

db.users.update({_id: "Jane"}, {$addToSet: {likes: "football"}}, {upsert: true})


No comments:

Post a Comment