Bradford
Bradford

Reputation: 4193

MongoDB - Can I use ObjectId as Key?

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?

Upvotes: 6

Views: 7817

Answers (3)

Scott Hernandez
Scott Hernandez

Reputation: 7590

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'}})

Upvotes: 7

Ram Dwivedi
Ram Dwivedi

Reputation: 470

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.

Upvotes: 1

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

try to use something like this

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

check this link for more details

Upvotes: 1

Related Questions