6

I have a list of stores and need to add notes to them. These notes need to have an ID so that they can be edited and deleted -- this is for a web app where an id parameter will contain a string used to identify the object. I'm not too familiar with MongoDB, but thought that having these notes in a map, with the ObjectId as the key, would be an easy solution to this. Please correct me if there is a better way to do this in MongoDB.

Anyway, when I try to use (new ObjectId()) as the key, I get a "invalid property id" error in the shell.

db.locations.update({_id: 'store1'}, {$set: {'notes': {(new ObjectId()): 'note1'}}})

Any ideas of what I'm doing wrong?

StaxMan
  • 113,358
  • 34
  • 211
  • 239
Bradford
  • 4,143
  • 2
  • 34
  • 44

3 Answers3

7

Keys are always strings in MongoDB. To set the nested field you must concat the strings together.

db.locations.update({_id: 'store1'}, {$set: {'notes.' + (new ObjectId()).toString(): 'note1'}})
Community
  • 1
  • 1
Scott Hernandez
  • 7,452
  • 2
  • 34
  • 25
  • Scott, this didn't seem to work for me in 1.6. It's as if it won't evaluate the expression where the key is. Your comment about keys are always strings is the answer I was looking for. – Bradford Dec 29 '10 at 18:07
  • It is possible you need to use a different construct for that. It was just a conceptual example. – Scott Hernandez Feb 20 '11 at 09:28
1

To me, it seems like you should have document where _id is for your notes. Current ID of 'store1' should be an attribute to this document. In other words, you need to tweak your schema here. You won't require to append object ID to the notes then. It'll also help to query this document faster later on.

Ram Dwivedi
  • 470
  • 3
  • 11
1

try to use something like this

db.locations.update({_id: 'store1'}, {$set: {'notes': { _id :  ObjectId("47cc67093475061e3d95369d")}}})

check this link for more details

Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42
  • 1
    Thanks for the reply, galimy. The snippet you provided above is using the ObjectId as the value instead of the key. I want to use ObjectId as the key for easier referencing. – Bradford Dec 29 '10 at 15:19
  • 1
    May be , it will be better if you will use "_id" as a simple string and create index for this property – Andrei Andrushkevich Dec 29 '10 at 15:30