Home > front end >  Why does this push not add a new field? (mongoDB)
Why does this push not add a new field? (mongoDB)

Time:10-20

I have a collection of restaurants where each document includes data such as the name, location, reviews, etc, and I'm attempting to push data which includes two reviews to the restaurant located in the borough of Brooklyn. This document happens to not currently have an array field of "reviews". According to everything I've looked at, the $push function should automatically add the array to the document, but it does not. Here is the code:

db.restaurants.updateOne(
  { borough: 'Brooklyn' },
  {
    $push: {
      reviews: {
        $each: [
          {
            name: 'Frank Zappa',
            date: 'January 3, 2019',
            rating: 3,
            comments: 'This restaurant is not good',
          },

          {
            name: 'Freddie Mercury',
            date: 'January 3, 2019',
            rating: 5,
            comments: 'This restaurant is my favorite',
          },
        ],
      },
    },
  }
);

The next command after this is to push the same reviews to another restaurant that does already have the array field "reviews", and also slice to 2. The only difference in code between these two is the filter and the slice modifier. The second works perfectly, the first does not.

Am I misunderstanding how push should work? Using push is a requirement in this case, though I did also try addToSet with the same

CodePudding user response:

https://mongoplayground.net/p/MxH01R4dxjU

it seems your Query is working fine plz check that you provided right values in the filter operation

CodePudding user response:

Turns out I didn't pay close enough attention to how many documents have the "borough" : "Brooklyn" field and there was more than one. Changed to updateMany and the problem was solved. Thanks for the time and attention!

  • Related