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?
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'}})
try to use something like this
db.locations.update({_id: 'store1'}, {$set: {'notes': { _id : ObjectId("47cc67093475061e3d95369d")}}})
check this link for more details
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.
精彩评论