Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Can I use ObjectId as Key?

Tags:

mongodb

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?

like image 591
Bradford Avatar asked Dec 29 '10 15:12

Bradford


1 Answers

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'}})
like image 101
Scott Hernandez Avatar answered Oct 11 '22 04:10

Scott Hernandez