Object.keys, how to get a list of keys in mongodb

為{幸葍}努か 提交于 2019-12-11 02:13:25

问题


{
"_id": "1",
"style": "13123",
"category": "dress",
"colors": {
    "Black": {
        "prestock": 50,
        "instock": 60,
        "inactive": 0
        },
    "Blue": {
        "prestock": 30,
        "instock": 0,
        "inactive": 0
        },
    "Red": {
        "prestock": 10,
        "instock": 60,
        "inactive": 0
        }
  }
}

i have above json, i need to access to prestock, instock, and inactive. but colors' value will change depending on styles. for example:

{
 "_id": "2",
 "style": "14321", 
 "category": "top",
 "colors": {
     "Green": {
        "prestock": 50,
        "instock": 60,
        "inactive": 0
         }, 
     "Yellow": {
        "prestock": 50,
        "instock": 60,
        "inactive": 0
         }
      }
}

how can i query this in mongodb? would this something that's related to Object.keys(obj)?

ps.if this is a duplicate question please guide me!

Thanks!


回答1:


A query like {"colors.*.prestock" : {$gte:30}} isn't possible according to SERVER-267, and I doubt this will be supported in the next years.

Your best bet is to change the schema to an array:

colors: [
 { "color" : "Green", "instock" : 50, ... },
 { "color" : "Yellow", "instock" : 50, ... },
]

Then you can query

db.foo.find( {"colors.prestock" : {$gte:30}} )

Note that this will return the entire object, including all colors, i.e. also those for which the query constraint doesn't hold. This could be solved using the aggregation framework, but again, only using $unwind which also requires colors to be an array.




回答2:


Is this is what you are looking for? MongoDB Get names of all keys in collection

If not, then the Application must have a list of keys or enum values that has all the possible combinations, you will have to Query and go through them.



来源:https://stackoverflow.com/questions/19301168/object-keys-how-to-get-a-list-of-keys-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!