4

I am trying to gain a fundamental understanding of how MongoDB works, and was unable to find this question addressed. I presume this is not possible, but maybe I am wrong?

Given the following JSON structure:

{
"bob": { "height": 68, "gender": "m" },
"sally": { "height": 48, "gender": "f" }
}

When this structure is deserialized into JavaScript, I am easily able to iterate the properties of this object to get a list of people. Note, that this list of people can/will be dynamic. Thus, sometimes "bob" won't exist, and sometimes "mike" might exist, etc.

However, with MongoDB queries, this does not seem to be possible. MongoDB appears to require data like this be in an array. Then I could query down to the "people" array, and then iterate over that.

I would like to confirm that, indeed, the MongoDB engine cannot iterate properties like JS can. If this is true, I guess this makes sense. Since the JSON structure represents both the data and the schema all in one, having dynamic properties like this might make the document difficult, if not impossible, to index. So maybe this is the reason? I am hoping someone can confirm.

I was hoping I could use MongoDB to store the same JSON structure returned my UI, but I am thinking that the structure will need to be modified to something like the following for data storage.

{ "people": [{
"name": "bob", "height": 68, "gender": "m" }, {
"name": "sally", "height": 48, "gender": "f" }]
}
Brian Shotola
  • 472
  • 3
  • 12
  • Have you looked http://stackoverflow.com/questions/2298870/mongodb-get-names-of-all-keys-in-collection it might provide some insight. – DaveStSomeWhere Mar 24 '15 at 17:48
  • Thanks @DaveCoast, in all my searching I did not see that. Very interesting. In my case it might help, but I would have to run the map-reduce operation, and from that result go back and query again. For the effort that would take, I am probably better off restructuring my data to fit into the DBMS better. – Brian Shotola Mar 25 '15 at 15:00

1 Answers1

2

That's right. MongoDB does not have functionality for manipulating documents based on the key name, besides explicitly naming the key. The one exception is server-side javascript, which you should avoid because of security and performance problems. The principle is "don't use data as keys"; data should be in values and the keys give specific, unchanging names that you use to construct queries. In your case, the most natural structure would seem to be having each document represent a person like so

{
    "name" : "bob",
    "height" : 68,
    "gender" : "m"
}

A priori I see no reason why the people should be grouped together in an array instead of separate documents. Some other factor in your use case might recommend it, though.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23