Merge all documents of collection into array

Hi,

Using pymongo:

self.db.command({‘buildInfo’:1})[‘version’]
‘4.4.3’

I would like to convert a doc like:

{
  "_id": "DOC1",
  "EL1": "my1",
  "EL2": [
    "my11"
  ],
  "EL3": [
    "my21",
    "my22",
    "my23"
  ],
  ...
}

into array in the same doc like:

{
  "_id": "DOC1",
  "DOC1": [
    {
	  "EL1": "my1",
	  "EL2": [
		"my11"
	  ],
	  "EL3": [
		"my21",
		"my22",
		"my23"
	  ]
	  ...
    }
  ]
}

I try:

my_collection.update(
  { "_id": "DOC1" },
  {
    "$set": {
      "DOC1": [
        {
          "$objectToArray": "$$ROOT"
        }
      ]
    }
  }
)

and

my_collection.update_one(
    {"_id": "DOC1"},
    [
        {"$set": {"DOC1": [{"$mergeObjects": ["$DOC1", {}]}]}}
    ]
)

but i give an error in each case:

The dollar ($) prefixed field ‘$objectToArray’ in is not valid for storage.

Is there a solution to update one directly without get all docs and set ?

Thanx in advance.

Welcome to the MongoDB community.

Did you look at this link node.js - MongoDB "The dollar ($) prefixed field is not valid for storage." - Stack Overflow?

1 Like

I am pretty sure the error message is different when you try

Because $objectToArray is not used at all. The error must be different. Please share as we might have a better idea of what is happening. In my case it worked with an error.

In the future, please avoid adding three little dots to your documents to show that you have more fields because we cannot cut-n-paste directly your documents.

1 Like

It’s not quite clear from your original post, but are you looking for a generic solution to update all at once or specific query you can apply to a document?

So you could do something like this:

db.getCollection("Test").updateMany(
{
    "_id": "DOC1"
},
[
    {
        $set:{
            newRoot:{
                _id:'$_id',
                "DOC1":['$$ROOT'],
            }
        }        
    },
    {
        $replaceRoot:{
            newRoot:'$newRoot'
        }
    }    
])

Which obviously needs you to pass in the ID so that the array can be named.

I was trying to find a generic solution where it would take a field value as the input to a field name, but could not work out a way of doing that…maybe someone else can.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.