Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage

I am trying to upsert a dataset to a Mongo collection.

  • The intended document may or may not exist.
    • If it does exist, it will have at least one item in an embedded document (zips), and should append to that document rather than overwrite it.
    • If it does not exist, it should insert the new document to the collection.

When I run the below code, I am getting an error: MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage.

I put this together based on the docs: https://docs.mongodb.org/getting-started/node/update/#update-multiple-documents

Versions: MongoDB (windows) = 3.2.0; mongodb (npm package) = 2.1.4

var query = {
 county: aCountyName, 
 state: aStateName
}    

var params = {
 '$set': {     
  county: 'Boone',
  state: 'MO',
  '$push': {
    zips: {
      '$each': [ '65203' ]
    }
  }
 }
}

(could also be)

var params = {
 '$set': {     
  county: 'Pierce',
  state: 'WA',
  '$push': {
    zips: {
      '$each': [ '98499', '98499' ]
    }
  }
 }
}

db.collection(collectionName).updateMany(query, params, {'upsert': true},
  function(err, results) {
    callback();
  }
);
like image 396
getglad Avatar asked Jan 14 '16 17:01

getglad


1 Answers

I don't think $push is valid within a $set. Instead try adding it as another parameter, e.g.:

var params = {
  '$set': {
    county: 'Pierce',
    state: 'WA'
  },
  '$push': {
    zips: {
      '$each': ['98499',
      '98499']
    }
  }
}
like image 134
Owain Williams Avatar answered Nov 12 '22 21:11

Owain Williams