MongoDB insert unique object into array (by author field)

Viewed 91

How do I:

  • Update an object in the reviews array, if an existing object with the same author exists
  • Insert a new object otherwise

(In other words: update a review if the author has already written one, and create a new one if they haven't)

Document structure:

{
    "_id": "(book id)",
    "title": "Title",
    "author": "Author",
    "reviews": [{
        "author": "(user id)",
        "rating": 4
    }],
}

This is what I've tried so far -- it only updates:

db.books.update_one(
    {"_id": ObjectId(book_id)},
    {"$set": {"reviews.$[elem]": {  # or $push etc.
        "author": user_id, "rating": rating}}},
    array_filters=[{"elem.author": user_id}])

Alternatively I have also tried result.modified_count == 0: then insert but this would insert a duplicate if the previous rating is the same as the new one (hence not updating anything and result.modified_count == 0)

Sorry for another similar question! Thank you in advance!

EDIT:

From the $addToSet operator page:

"...you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element."

However I'm still interested if anyone has a way to do this (it doesn't have to be in one query)!

1 Answers
Related