1

I have array like this :

"organizationIds" : [ 
       ObjectId("60373852f64bf2cc8c73136d"), 
       ObjectId("60373852f64bf2cc8c73139d"), 
       ObjectId("60373852f64bf2cc8c73138d")
   ]

I would like to this turn to object:

"organization":{
 "ObjectId("60373852f64bf2cc8c73136d")":{
owner: false
 },
 "ObjectId("60373852f64bf2cc8c73138d")":{
owner: false
 }
 "ObjectId("60373852f64bf2cc8c73138d")":{
owner: true
 }
}

I have tried using:

db.getCollection('users').aggregate([{$addFields:{organizationsPermissions:{$arrayToObject:"$organizationIds"}}},])

but I keep getting error"Unrecognised input type format for $arrayToObject: objectId".

Is there a way to reach my wanted result?

1 Answer 1

1

Here's the solution using aggregation framework.

$arrayToObject works on array with formats like this:

[ [ "item", "abc123"], [ "qty", 25 ] ]

So first convert your organizationIds array into that format by using the pipeline below which uses $map which works exactly like array map function in Javascript. Also ObjectId cant be used as object key so converted it into string as well.

{
"$addFields": {
  "organizationIds": {
    $map: {
      input: "$organizationIds",
      as: "org",
      in: {
        $concatArrays: [
          [
            {
              $toString: "$$org"
            }
          ],
          [
            {
              owner: false
            }
          ]
        ]
      },
      
    }
  }
}
}

Now you can use $arrayToObject.

{
"$addFields": {
  "organizationIds": {
    "$arrayToObject": "$organizationIds"
  }
}
}

Working example here. https://mongoplayground.net/p/Y8PNyRn7elA

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

3 Comments

db.getCollection('users').aggregate([ {$addFields:{organizationsPermissions:{$arrayToObject:{$map:{ "input":"$organizationIds", "as":"out", "in":{ "k":{$toString:"$$out"}, "v":{"owner":false} } }}}}} ]) I used code above to make it happen. Which way would be more optimal for usage?
This will work as well, I broke it down for simplicity. As for optimal I guess your solution would be more efficient as you are not transforming and saving two times.
Sadly we scrapped this data storage idea and went with another way. Yes your way worked too. Thanks for help

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.