1

Lets say we have a document like this

{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : "Math"
}

And we changed over mind and want to push more things to Data->Like so it looks like;

{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : ["Math", "Science"]
}

All the atomic operators like $push, $pushAll and $addToSet works just when Data->Like already is an array.

I´m using the php-driver. In this example there is no meaning to not set the Data->Like to an array at the beginning but it does not work like that in my code ;(

Hope you can help me and sorry for my bad English ;) Thanks!

1 Answer 1

1

You'll have to iterate over all your documents and change the value to an array. For example, you can do that with:

$m = new Mongo();
$c = $m->yourdbname->yourcollectionname;

foreach ( $c->find() as $r )
{
    if ( !is_array( $r['Data']['Like'] ) )
    {
        $c->update( array( '_id' => $r['_id'] ), array( '$set' => array( 'data.like' => array( $r['data']['like'] ) ) ) );
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I do not want to do it with all my documents but I think I can mange to fix it in the way I want. I hoped for an operator that just added the data ;(

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.