1
{
    _id :{
        "foo" : "abc"
    },
    "time" :[],
    "bar": [
        [],
        []
    ]
}

Expected Output abc become the key bar

{
    "_id" :{
        "foo" : abc
    },
    "time" :[],
    "abc": [
        [],
        []
    ]
}
6
  • Check $rename operator. Commented Nov 5, 2020 at 14:57
  • it's not working in my case, I have multiple documents, or can you describe me in detail or post some query, that would be helpful Commented Nov 5, 2020 at 15:00
  • Can you provide a better example and explanation?. With this data I'm assuming you only want to rename bar to abc. But, is abc given or is neccesary get from the _id.foo field? Commented Nov 5, 2020 at 15:02
  • yes, it is compulsory to get from _id.foo. so, abc is dynamically changing, but bar is the key name, it contains the values of abc Expeceted result is abc as the name of array and get values. Commented Nov 5, 2020 at 15:05
  • do you want to update update() this documents? or just want to get and display aggregate() ? Commented Nov 5, 2020 at 15:12

1 Answer 1

1

You can try,

  • $arrayToObjects to set foo as k(key) and bar as v(value) and convert to object format
  • $mergeObjects to merge $$ROOT and above operation result
  • $replaceRoot to replace above both merge object result in root
  • $project to remove bar field because we don't needed
db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { $arrayToObject: [[{ k: "$_id.foo", v: "$bar" }]] },
          "$$ROOT"
        ]
      }
    }
  },
  { $project: { bar: 0 } }
])

Playground

Sign up to request clarification or add additional context in comments.

11 Comments

your sol is work if I have documents as an array but I don't have the document as array. I have structure like this { _id :{ "foo" : "abc" }, "time" :[], "bar": [ [], [] ] } your sol is work IF [ _id :{ "foo" : "abc" }, "time" :[], "bar": [ [], [] ] ]
Yes its an array its just structure of playground website, you can run this query in your platform this will work.
When I run it , I get error message : '$arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys:1' on server .
have you executed same query?
yes, I executed, the same query as you give. but as I said I have one document with { } your query is working with [ ].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.