Refresh MongoDB Subtalk if Parent Document May Not Exist

Here is my data, consisting of a collection of books, with a subcategory of books.reviews.

books = [{
    _id: ObjectId("5558f40ad498c653748cf045"),
    title: "Widget XYZ",
    isbn: 1234567890,
    reviews: [
        {
            _id: ObjectId("5558f40ad498c653748cf046"),
            userId: "01234",
            rating: 5,
            review: "Yay, this great!"
        },
        {
            _id: ObjectId("5558f40ad498c653748cf047"),
            userId: "56789",
            rating: 3,
            review: "Meh, this okay."
        }
    ]
}]

In Node.js (using Mongoose), I need users to be able to submit reviews through a form by submitting a review and isbn books to the server with the following conditions:

  • If the book does not already exist with a specific isbn, add it and then add a review (it obviously does not exist yet).
  • If the book exists ...
    • If a review for this book does not exist for this user, add it.
    • If a review exists for this book for this user, update it.

I can do this with 4 separate queries, but I know that this is not optimal. What is the minimum number of queries I could use (and, of course, what kind of queries)?

+4
1

3 :

  • , . $set
  • , . $push
  • . {upsert:1} a $setOnInsert

(, MongoDB ).

, :

// Case 1:
db.books.update({isbn:'1234567890',
                 review: { $elemMatch: {userID: '01234'}}},
                {$set: {'review.$.rating': NEW_RATING}}
               )

// Case 2:
db.books.update({isbn:'1234567890',
                 review: { $not: { $elemMatch: {userID: '01234'}}}},
                {$push: {review: {rating: NEW_RATING, userID:'01234'}}}
               )

// Case 3:
db.books.update({isbn:'1234567890'},
                {$setOnInsert: {review: [{rating: NEW_RATING, userID:'01234'}]}},
                {upsert:1}
               )

, . - idempotent. . . , . . , ( : , ).
, , .

, MongoDB , update , .

+3

All Articles