Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

How to invert a MongoDB aggregation result?

I apologize if this is a silly question, but is there an easy way to invert a MongoDB result? My aggregation pipeline returns this:

[
  {
    email: "[email protected]",
    phone: "1290740373"
  },
  {
    email: "[email protected]",
    phone: "1455414441"
  },
  {
    email: "[email protected]"
  }
  ...
]

Is there a way to get something like this out:

{
"[email protected]": 1,
"1290740373": 1,
"[email protected]": 1,
"1455414441": 1,
"[email protected]": 1
}

I am fully aware that a library like lodash can do that with one line of code inside the app, but I was hoping to accomplish this on the DB level if it's not too cumbersome.

question from:https://stackoverflow.com/questions/65623584/how-to-invert-a-mongodb-aggregation-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have two challenges, first you have to convert field values to field names. This is achieved with $objectToArray and $arrayToObject.

Second you have to translate all documents into one document. For this I use $group and $reduce

db.collection.aggregate([
  { $unset: "_id" },
  // transform field values into field names 
  { $set: { data: { $objectToArray: "$$ROOT" } } },
  {
    $set: {
      data: {
        $map: {
          input: "$data",
          in: { k: "$$this.v", v: 1 }
        }
      }
    }
  },
  { $replaceRoot: { newRoot: { $arrayToObject: "$data" } } },
  // Merge all documents into one
  {
    $group: {
      _id: null,
      data: { $push: "$$ROOT" } 
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $reduce: {
          input: "$data",
          initialValue: {},
          in: { $mergeObjects: [ "$$value", "$$this" ] }
        }
      }
    }
  }
])

See Mongo playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...