Promote subfields to top level in projection without listing all keys

青春壹個敷衍的年華 提交于 2019-12-29 01:24:49

问题


I have documents like {'a': 1, 'z': {'b': 2, 'c': 3,}}.

I want {'a': 1, 'b': 2, 'c': 3}.

I can do this with

aggregate({'$project': {'b': '$z.b', 'c': '$z.c'}})

Is it possible to do it without listing all of the keys in the subdocument manually?


回答1:


With MongoDB 3.4 you can use $objectToArray and $arrayToObject with $replaceRoot in order to change this:

db.wish.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": {
        "$concatArrays": [
          [{ "k": "a", "v": "$a" }],
          { "$objectToArray": "$z" }
        ]
      }
    }
  }}
])

Or even this long incantation without even specifying the "a" property:

db.wish.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": {
        "$reduce": {
          "input": {
            "$filter": {
              "input": { "$objectToArray": "$$ROOT" },
              "as": "r",
              "cond": { "$ne": [ "$$r.k", "_id" ] }
            }
          },
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              { "$cond": {
                "if": {  "$gt": [ "$$this.v", {} ] },
                "then": { "$objectToArray": "$$this.v" },
                "else": ["$$this"]
              }}
            ]
          }  
        } 
      }
    }
  }}
])  

Both produce:

{ "a" : 1, "b" : 2, "c" : 3 }

The funny use of $concatArrays should not be necessary in future versions since there will be a $mergeObjects operator which will make that a bit cleaner.

But you can basically just do the same thing in client code pretty simply. For example in JavaScript for the shell:

db.wish.find().map( doc => (
  Object.assign({ a: doc.a }, doc.z )
))

Or the version without the "a" again:

db.wish.find().map( doc => 
  Object.keys(doc).filter(k => k !== '_id').map(k => 
   ( typeof(doc[k]) === "object" ) ? 
     Object.keys(doc[k]).map(i => ({ [i]: doc[k][i] }))
       .reduce((acc, curr) => Object.assign(acc,curr),{})
     : { [k]: doc[k] }
  ).reduce((acc,curr) => Object.assign(acc,curr),{})
)

Produces the same output

{ "a" : 1, "b" : 2, "c" : 3 }


来源:https://stackoverflow.com/questions/44752934/promote-subfields-to-top-level-in-projection-without-listing-all-keys

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